Function.prototype.handWrittenBind = function(){
//const args = Array.from(arguments);
//const thisArg = args.shift(); // 将指针和参数分开
//const thisArg = thisArg || window; //判断传入的第一个参数
if(typeof this !=='function') throw 'caller must be a function' // 判断是否函数在调用此方法
let callerThis = this; // 保存调用者的this 在返回函数当调用的者的构造函数时使用
let thisArg = arguments[0] // 获取第一个参数
let args = Array.prototype.slice.call(arguments, 1); //除了指针意外的其他参数
const resultFn = function(){
let fnArgs = Array.prototype.slice.call(arguments) // 调用返回函数时传的参数
// this instanceof callerThis 用来判断当前的返回函数是被当做构造函数执行了
// 传入null/undefined的时候将执行js全局对象浏览器中是window
callerThis.apply(this instanceof callerThis ? this : thisArg, args.concat(fnArgs))
}
resultFn.prototype = Object.create(callerThis.prototype) //将返回的函数的原型指向调用者的实例上
return resultFn
}
obj = {
name:'张三',
fn:function(){
console.log(this);
}
}
obj.fn.handWrittenBind([1,2,3])()
obj.fn.handWrittenBind(null)()
手写js中的bind方法
于 2022-11-02 16:29:54 首次发布