js实现bind方法

//目标函数
function fun(...args) {
     console.log(this);
     console.log(args);
}
//目标函数原型对象上的一个方法cher
func.prototype.cher = function () {
    console.log(1);
}

//bind传入参,一个是要改变this指向的对象,后面的是要传入的实参数值
Function.prototype.myBind = function (obj,...args) {

        var _that = this;
        //bing会返回一个新的函数
        var newBind = function(...list) {
      //如果作为了构造函数,this指向构造函数,否则就指向传入的对象
       var targetObj = this instanceof newBind ? this : obj; 
 
          //使用apple方法把this指向改变
          _that.apply(targetObj ,[...list,...args]);
        }
        //在用bind改变this指向的时候,返回的函数不会立即执行。如果用返回的函数作为构造函数实例化一个对象的时候,这个对象的原型对象还是目标对象的原型对象,所以要纠正过来
        newBind.prototype = Object.create(_that.prototype);
        newBind.prototype.constructor = _that;

        //返回这个函数
        return newBind;
}

var fn2 = fun.myBind({a:1},4,3);
var newFn2 = new fn2(1,2);            //newBind{}   1,2,4,3
console.log(newFn2);                 //newBind{}
console.log(newFn2.cher());          //1

 

转载于:https://www.cnblogs.com/ninefrom/p/9815588.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值