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; //要改变this执行的目标函数
//bing会返回一个新的函数
var newBind = function(...list) {
//如果作为了构造函数,this指向构造函数,否则就指向传入的对象
var targetObj = this instanceof newBind ? this : obj;
//使用apple方法把this指向改变
_that.apply(targetObj ,[...list,...args]);
}
////自己实现的bind函数,如果把返回的函数当做构造函数,就找不到目标函数原型上的方法,所以新函数继承目标函数原型
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