返回

函数的三大方法:call()、apply()、bind(),提升开发效率的利器

前端

  1. call()方法
    call()方法允许我们以显式的方式指定函数的this值。它接受两个参数:第一个参数是要指定this值的对象,第二个参数及以后的参数是传递给函数的实际参数。

例如,我们有一个对象person,它有一个方法sayName(),该方法将返回this.name的值。如果我们想调用person.sayName()方法,但同时又想将this值指定为另一个对象student,我们可以使用call()方法。

const person = {
  name: 'John Doe',
  sayName: function() {
    return this.name;
  }
};

const student = {
  name: 'Jane Doe'
};

console.log(person.sayName()); // John Doe
console.log(person.sayName.call(student)); // Jane Doe

在上面的示例中,我们首先调用person.sayName()方法,这将返回John Doe。然后,我们使用call()方法将person.sayName()方法应用于student对象,并将student对象作为this值传递给该方法。这将返回Jane Doe,因为this值现在指向student对象。

2. apply()方法

apply()方法与call()方法类似,但它接受的参数列表不同。apply()方法的第一个参数是要指定this值的对象,第二个参数是一个数组,其中包含要传递给函数的实际参数。

const person = {
  name: 'John Doe',
  sayName: function() {
    return this.name;
  }
};

const student = {
  name: 'Jane Doe'
};

console.log(person.sayName()); // John Doe
console.log(person.sayName.apply(student, ['Jane Doe'])); // Jane Doe

在上面的示例中,我们使用apply()方法将person.sayName()方法应用于student对象,并将['Jane Doe']数组作为实际参数传递给该方法。这将返回Jane Doe,因为this值现在指向student对象,并且['Jane Doe']数组中的值被传递给该方法作为实际参数。

3. bind()方法

bind()方法与call()和apply()方法不同,它不立即调用函数,而是返回一个新的函数。这个新函数的this值被绑定到bind()方法的第一个参数,并且当新函数被调用时,实际参数将被传递给新函数。

const person = {
  name: 'John Doe',
  sayName: function() {
    return this.name;
  }
};

const student = {
  name: 'Jane Doe'
};

const sayName = person.sayName.bind(student);

console.log(sayName()); // Jane Doe

在上面的示例中,我们使用bind()方法将person.sayName()方法绑定到student对象。这将返回一个新的函数sayName,其this值被绑定到student对象。当我们调用sayName()函数时,this值将指向student对象,并且sayName()函数将返回Jane Doe。

总结

call()、apply()和bind()方法都是用来改变函数执行时this指向的,但它们在参数的传递方式和返回值方面有所不同。

  • call()方法接受两个参数:第一个参数是要指定this值的对象,第二个参数及以后的参数是传递给函数的实际参数。
  • apply()方法接受两个参数:第一个参数是要指定this值的对象,第二个参数是一个数组,其中包含要传递给函数的实际参数。
  • bind()方法与call()和apply()方法不同,它不立即调用函数,而是返回一个新的函数。这个新函数的this值被绑定到bind()方法的第一个参数,并且当新函数被调用时,实际参数将被传递给新函数。

这些方法在JavaScript开发中非常有用,可以帮助我们改变函数的执行上下文,从而实现更灵活的代码编写。