返回

函数背后的原理——bind()、softBind()、call()和apply()

前端







## **bind()函数** 

bind()函数用于将函数绑定到特定对象,以便在该对象上调用该函数。这在需要将函数作用于另一个对象时非常有用,例如,当你想将函数添加到对象时,或者你想创建一个新的函数,该函数与另一个对象共享相同的this值。

**语法** 

bind(thisArg, ...argArray)


**参数** 

* **thisArg** :要将函数绑定到的对象。
* **argArray** :要传递给函数的参数数组。

**返回值** 

一个新的函数,该函数被绑定到thisArg并接受argArray作为参数。

**示例** 

const person = {
name: 'John Doe',
greet: function() {
console.log(Hello, my name is ${this.name}!);
}
};

const boundGreet = person.greet.bind(person);
boundGreet(); // Hello, my name is John Doe!


## **softBind()函数** 

softBind()函数与bind()函数非常相似,但它有一个重要的区别:softBind()函数不会改变this的值。这意味着你可以将softBind()函数用于那些不需要改变this值的情况,例如,当你想创建一个新的函数,该函数与另一个对象共享相同的方法时。

**语法** 

softBind(thisArg, ...argArray)


**参数** 

* **thisArg** :要将函数绑定到的对象。
* **argArray** :要传递给函数的参数数组。

**返回值** 

一个新的函数,该函数被绑定到thisArg但不会改变this的值。

**示例** 

const person = {
name: 'John Doe',
greet: function() {
console.log(Hello, my name is ${this.name}!);
}
};

const softBoundGreet = person.greet.softBind(person);
softBoundGreet(); // Hello, my name is John Doe!


## **call()函数** 

call()函数用于将函数调用到特定对象上,并使用指定的参数调用该函数。这在需要立即调用函数时非常有用,例如,当你想在某个事件发生时调用函数时。

**语法** 

call(thisArg, ...argArray)


**参数** 

* **thisArg** :要将函数调用到的对象。
* **argArray** :要传递给函数的参数数组。

**返回值** 

函数的返回值。

**示例** 

const person = {
name: 'John Doe',
greet: function() {
console.log(Hello, my name is ${this.name}!);
}
};

person.greet.call(person); // Hello, my name is John Doe!


## **apply()函数** 

apply()函数与call()函数非常相似,但它有一个重要的区别:apply()函数接受一个参数数组,而call()函数接受一个参数列表。这意味着apply()函数可以用于那些需要传递大量参数的情况,例如,当你想将函数应用于一个数组时。

**语法** 

apply(thisArg, argArray)


**参数** 

* **thisArg** :要将函数调用到的对象。
* **argArray** :要传递给函数的参数数组。

**返回值** 

函数的返回值。

**示例** 

const person = {
name: 'John Doe',
greet: function() {
console.log(Hello, my name is ${this.name}!);
}
};

person.greet.apply(person, ['John', 'Doe']); // Hello, my name is John Doe!


## **总结** 

bind()、softBind()、call()和apply()函数都是JavaScript中非常有用的函数,它们允许我们将函数与特定对象相关联,以便在该对象上调用该函数。这些函数之间的区别在于bind()函数会改变this的值,softBind()函数不会改变this的值,call()函数立即调用函数,apply()函数接受一个参数数组。