js call, apply, bind的简单实现

call 和apply是在传入的上下文中直接调用相应的方法, 而bind返回的是函数, 下面为其简单实现:

call: 

Function.prototype.myCall = function (){
            let args = [...arguments];
            let context = args.shift();
            context = typeof context != 'object' ? window : context || window; 
            context.fn = this;
            let result = context.fn(args);
            delete context.fn;
            return result;
        }
        var name = 'zhou';
        let person = { 'name': 'santal'};

        function sayName(str){
            console.log(this.name + ' ' + str);
            return this.name
        }
        sayName.myCall(person, 'hello'); // 'santal'
        sayName('world'); // 'zhou'
        sayName.myCall('你好'); // zhou    // 上下文为window

apply: 

Function.prototype.myApply = function (){
            let args = arguments[1];
            let context = arguments[0];
            context = typeof context != 'object' ? window : context || window; 
            context.fn = this;
            let result = context.fn(...args);
            delete context.fn;
            return result;
        }

bind: 

Function.prototype.myBind = function (){    
            let args = [...arguments];
            let context = args.shift();
            context = typeof context != 'object' ? window: context || window;
            context.fn = this;
            return function(innerArgs){ // 返回函数的参数
                console.log(innerArgs)
                context.fn(args);
            }
        }
        var name = 'zhou';
        var sex = 'female';
        let person = { 'name': 'santal', 'sex': 'male'};

        function sayName(){
            console.log(this.name+ ', '+ this.sex)
        }
        sayName();
        sayName.myBind(person, 'a', 'b')('这个世界很美好');

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值