详解什么是call、apply、bind
call
、apply
和 bind
是 JavaScript 中用于改变函数执行上下文(即 this
的指向)的三个方法。它们都属于 Function.prototype
,因此所有函数都可以使用。
1. call的用法:
调用一个函数,并指定该函数内部的 this
值,同时可以传递参数,用“,”逗号分割
2. apply的用法:
与 call
类似,也是调用函数并指定 this
值,但参数是以数组形式传入。
3. bind的用法:
创建一个新的函数,并绑定该函数内部的 this
值,不会立即执行函数。
例子:
let dog = {name: '狗狗',age: 2,sayName: function () {console.log('我是', this.name)},eat: function (food1: any, food2: any) {console.log('我喜欢吃', food1 + '和' + food2)}
}let cat = {name: '猫猫',age: 5,
}
//call可以调用函数,改变函数中的this指向
dog.sayName.call(cat) //我是猫猫
dog.eat.call(cat, '鱼', '猫粮') //我喜欢吃鱼和猫粮//apply可以调用函数,改变函数中的this指向
dog.eat.apply(cat, ['鱼', '猫粮'])//我喜欢吃鱼和猫粮//bind可以调用函数,改变函数中的this指向
dog.eat.bind(cat, '鱼', '猫粮')//不会立即打印,需要赋值let fun=dog.eat.bind(cat, '鱼', '猫粮')
fun();//我喜欢吃鱼和猫粮