记录 call和apply的实现

126 阅读1分钟
简单实现个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); // '张三',18,中国
**想达到 obj2.logFunc('张三',18) // '张三',18,'home'
这样就运用了隐式绑定知识点 来实现this指向的改变 **
来实现
 Function.prototype.myCall = function(thisArg){
    //  调用myCall的必须是函数
    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); // 张三 18 home

再来实现 apply 
基于myCall的代码实现  改动很小 只有参数那一部分
 Function.prototype.myApply = function(thisArg){
    //  调用myCall的必须是函数
    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]); // 张三 18 home

简单的实现,如有错误,欢迎指出;