call、apply和bind用法和手写

//call、apply、bind都是改变this指向的方法

//es5中 谁调用就this指针就指向谁
//call和apply的区别传参
var name = 'windowName'
var a = {
	name:'cherry',
	fn:function(a,b){
		console.log('name',this.name)
	},
	fn1:function(a,b){
       console.log(a+b);
    }
}
var b = a.fn1;
b.call(a,1,2)  //3
b.apply(a,[1,2]) //3
b.bind(a,1,2)() // 3
//手写call
 Function.prototype.mycall = function(ctx){
        ctx = ctx || window;
        ctx._fn = this;
        let arg = [...arguments].slice(1);
        let result = ctx._fn(...arg);
        delete ctx._fn;
        return result
    }

Function.prototype.myCall = function(ctx,...arg){
   ctx = ctx || window;
    ctx._fn = this
    let result = ctx._fn(...arg)
    delete ctx._fn
    return result
}
Function.prototype.myApply = function(ctx,arg){
    ctx = ctx || window;
    ctx._fn = this
    let result = ctx._fn(...arg)
    delete ctx._fn
    return result
}
Function.prototype.myBind = function(ctx){
    let that = this;
    ctx = ctx || window;
    let arg = [...arguments].slice(1)
    return function(){
        that.apply(ctx,arg.concat(...arguments))
    }
}
Function.prototype.newBind = function (that) {
    if (typeof this !== 'function') {
        throw new TypeError('Error')
    }
    const args = [...arguments].slice(1);
    const fn = this;
    return function () {
        fn.apply(that)
    };
    // 返回一个函数
    return function F() {
        // 因为返回了一个函数,如果是new的话this就要指向新创建的对象了
        if (this instanceof F) {
            return new fn(...args, ...arguments)
        }
        return fn.apply(that, args.concat(...arguments))
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值