简单实现个call 和 apply
我们都很熟悉call和apply是用来改变函数的this指向,
call和apply的参数略有不同,
apply 第二个参数是个数组,call第一个参数往后是个参数列表,
实现 call和apply 利用到了 this的隐式绑定,
所谓隐式绑定,在我理解,就是函数被调用的位置所在的词法作用域
比如
let obj = {
address:'中国',
logFunc: function(name,age){
console.log(name,age,this.address)
}
};
let obj2 = {address:'home'};
obj.logFunc('张三',18);
**想达到 obj2.logFunc('张三',18)
这样就运用了隐式绑定知识点 来实现this指向的改变 **
来实现
Function.prototype.myCall = function(thisArg){
if(typeof this !== 'function'){
throw new TypeError('调用myCall必须是个函数!')
}
let args = [...arguments].slice(1);
let fn = Symbol(this);
thisArg[fn] = this;
let result = thisArg[fn](...args);
delete thisArg[fn];
return result;
}
来快乐的验证
obj.logFunc.myCall(obj2,'张三',18);
再来实现 apply
基于myCall的代码实现 改动很小 只有参数那一部分
Function.prototype.myApply = function(thisArg){
if(typeof this !== 'function'){
throw new TypeError('调用myApply必须是个函数!')
}
let args = arguments[1] || [];
let fn = Symbol(this);
thisArg[fn] = this;
let result = thisArg[fn](...args);
delete thisArg[fn];
return result;
}
来快乐的验证
obj.logFunc.myApply(obj2,['张三',18]);
简单的实现,如有错误,欢迎指出;