说说bind,call,apply的区别?并手写实现一个bind方法。
考点:
- bind,call,apply的作用和区别
- 如何手动实现call和bind
答案:
apply:第一个参数是null,在非严格模式下,第一个参数为null或者undefined时会自动替换为指向全局对象,apply()的第二个参数为数组或类数组
call:call()是apply()的一颗语法糖,作用和apply()一样,同样可实现继承,唯一的区别就在于call()接收的是参数列表,而apply()则接收参数数组
bind:bind()的作用与call()和apply()一样,都是可以改变函数运行时上下文,区别是call()和apply()在调用函数之后会立即执行,而bind()方法调用并改变函数运行时上下文后,返回一个新的函数,供我们需要时再调用。
let animal = {
name: 'cat'
};
function say(sex) {
console.log('hello,' + this.name);
return sex;
}
//手动实现call
Function.prototype.myCall = function(context = window) {
let args = [...arguments].slice(1); //参数
context.fn = this;
let result = context.fn(...args);
delete context.fn;
return result;
};
//手动实现bind
Function.prototype.myBind = function(context = window) {
let self = this;
let args = [...arguments].slice(1); //参数
return function() {
let newArgs = [...args, ...arguments];
return self.myCall(context, ...newArgs);
};
};
let animalSay = say.myBind(animal, 'woman');
console.log(animalSay('man'));call()、apply()和bind()都是用来改变函数执行时的上下文,可借助它们实现继承。
参考: