区别
1、参数传递方式:
call和bind接收参数列表,参数之间用逗号分隔apply接收参数数组或类数组对象。 2、执行时机:call和apply会立即执行函数。bind返回一个新的函数,需要手动调用才会执行。 3、返回值call和apply返回函数的执行结果。bind返回一个新的函数。 4、上下文对象- 如果传入的上下文对象为
null或undefined,在非严格模式下,this会被指向全局对象window;在严格模式下,this保持为null或undefined。
手写
1、call
Function.prototype.call2 = function(context, ...args) {
//调用call的只能是函数
if (typeof this !== 'function') {
throw new TypeError('call2 callback is not a function');
}
//this参数可以传null 当传null的时候 视为指向window
context = context || window;
//将函数设为对象的属性
const fn = Symbol();
context[fn] = this;
//执行函数
const result = context[fn](...args);
//删除函数
delete context[fn];
//返回结果
return result;
};
var a = 1
const obj = {
a: 2,
test: function(){
console.log(this, this.a)
}
}
obj.test()
obj.test.call2()
obj.test.call()
2、apply
//apply 与 call的区别只是参数形式不一样 拿来解构一下就行
Function.prototype.apply2 = function(context, args) {
if (typeof this !== 'function') {
throw new TypeError('apply2 callback is not a function');
}
context = context || window;
const fn = Symbol();
context[fn] = this;
const result = args ? context[fn](...args) : context[fn]();
delete context[fn];
return result;
};
3、bind
//bind会创建一个改变了this指向的新函数
Function.prototype.bind2 = function(context) {
if (typeof this !== 'function') {
throw new TypeError('bind2 callback is not a function');
}
//拿到传进来的新指向context 返回一个函数(多个参数) 函数的值是改变指向执行后的结果
const _this = this;
return function(...args) {
return _this.apply(context, args);
};
};