Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js apply call bind区别

作者:泪﹌无痕   发布日期:2025-09-05   浏览:73

// 使用 apply 方法
function Product(name, price) {
    this.name = name;
    this.price = price;
}

function Food(name, price) {
    Product.apply(this, arguments);
    this.category = 'food';
}

const cheese = new Food('cheddar', 5);
console.log(cheese); // Food { name: 'cheddar', price: 5, category: 'food' }

// 解释:apply 方法调用一个函数,将函数绑定到指定的 this 值,并传入一个参数数组。这里我们将 Product 的构造函数应用到 Food 实例上。

// 使用 call 方法
function greet(greeting) {
    console.log(greeting + ', my name is ' + this.name);
}

const person = { name: 'Alice' };
greet.call(person, 'Hello');
// 输出: Hello, my name is Alice

// 解释:call 方法类似于 apply,但它接受的是参数列表而不是参数数组。这里我们将 greet 函数的 this 绑定到 person 对象,并传递参数。

// 使用 bind 方法
function greet2(greeting) {
    console.log(greeting + ', my name is ' + this.name);
}

const greetAlice = greet2.bind({ name: 'Alice' });
greetAlice('Hi');
// 输出: Hi, my name is Alice

// 解释:bind 方法创建一个新的函数,当这个新函数被调用时,this 被绑定到 bind 的第一个参数。这里我们创建了一个新的函数 greetAlice,它总是将 this 绑定到 { name: 'Alice' }。

上一篇:js gzip

下一篇:js call apply bind区别

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站