
在JavaScript中,call, apply, 和 bind 是函数对象的三个非常重要的方法,它们都用于改变函数的上下文(即函数内部的 this 值)。尽管它们的作用相似,但它们在使用方式上有所不同。
1. call()
call() 方法可以调用一个函数,其具有一个指定的 this 值和分别提供的参数。
语法:
function.call(thisArg, arg1, arg2, ...)- thisArg:在函数运行时使用的- this值。
- arg1,- arg2, ...:指定的参数列表。
示例:
function Product(name, price) {
  this.name = name;
  this.price = price;
}
function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}
console.log(new Food('cheese', 5).name); // 输出: cheese在这个例子中,Product 函数通过 call 方法被 Food 函数调用,这样 Food 函数就可以使用 Product 函数的逻辑。
2. apply()
apply() 方法与 call() 类似,唯一的区别是 apply 接受一个参数数组,而不是一系列参数列表。
语法:
function.apply(thisArg, [argsArray])- thisArg:在函数运行时使用的- this值。
- argsArray:一个数组或者类数组对象,其中的数组元素将作为单独的参数传给函数。
示例:
function sum(a, b) {
  return a + b;
}
function callSum(a, b) {
  return sum.apply(null, [a, b]); // sum函数的this值在这里不重要,所以传null
}
console.log(callSum(1, 2)); // 输出: 33. bind()
bind() 方法创建一个新的函数,当被调用时,其 this 值被设定为提供的值,其参数列表中的序列将被传递给原函数。
语法:
function.bind(thisArg[, arg1[, arg2[, ...]]])- thisArg:当绑定函数被调用时,该参数会作为原函数运行时的- this值。
- arg1,- arg2, ...:当绑定函数被调用时,这些参数将置于实参之前传递给原函数。
示例:
const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};
const unboundGetx = module.getX;
console.log(unboundGetx()); // 输出: undefined,因为此时的this指向全局对象
const boundGetx = unboundGetx.bind(module);
console.log(boundGetx()); // 输出: 42,因为this被绑定到module对象总结
- call和- apply都用于立即执行函数,并且可以指定函数内的- this值。
- call接受参数列表,而- apply接受一个参数数组。
- bind创建一个新的函数实例,其- this值被永久绑定到- bind调用时传入的值,不会立即执行函数。
这些方法在处理回调函数、事件处理器、构造函数继承等场景中非常有用。
本文来自投稿,不代表本站立场,如若转载,请注明出处:
  
  
  
好厉害好厉害好厉害好厉害好厉害