js实现bind方法

时间:2024-04-24 09:05:31
//目标函数
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());   //