// 使用 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
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站