Function.prototype.bind = function(o, ...rest) {
var self = this;
var tempFn = function() {};
//tempFn是一个中转构造函数,位于调用完bind后生成的函数的原型链上,
//如果调用bind的函数是构造函数那么函数内部的this指向new时后台自动生成的空对象,
//这个空对象以该函数构造函数,所以可以使用instanceof来测试调用函数是否是构造函数
var fn = function() {
self.apply(this instanceof tempFn ? this : o || window, rest);
}
fn.prototype = Object.create(tempFn.prototype);
//或者是-------------------
// fn.prototype = new tempFn();
// fn.prototype.constructor = fn;
return fn;
}
剑指offer(十七):手动实现bind函数
最新推荐文章于 2024-01-27 17:03:46 发布