手写call与apply函数

60 阅读1分钟

call与apply

相同点:都能改变函数中this的指向

不同的是:call传递多个参数以逗号隔开,apply多个参数得放在数组中

以下是 手写call的方法

let person={
            name:"科比",
            sayName:function(){
               return console.log(this.name,arguments);
            }
        }
        let father={
            name:"乔丹"
        }
        Function.prototype.mycall=function(context){
            console.log(context);
            context=context || window;
            console.log(this); 
            if(typeof this !=="function"){
                return
            }
            let args=[...arguments].slice(1);
            context.fn=this;
            let res=context.fn(...args)
            delete context.fn
            return res;
        }
        person.sayName.call(father,1,2,3);
        person.sayName.mycall(father,1,2,3);

apply

let person={
            name:"科比",
            sayName:function(){
               return console.log(this.name,arguments);
            }
        }
        let father={
            name:"乔丹"
        }
Function.prototype.myApply=function(context){
            if(typeof this !== "function"){
                return
            }
            context=context || window;
            context.fn=this;
            let args=arguments[1];
            let res=context.fn(...args);
            delete context.fn;
            return res;
        }
        person.sayName.apply(father,[1,2,3]);
        person.sayName.myApply(father,[1,2,3]);