Function.prototype.bind = function(context) { //调用 bind 的不是函数报错 if (typeofthis !== "function") { thrownewError("Function.prototype.bind - what is trying to be bound is not callable"); }
let self = this; let args = Array.prototype.slice.call(arguments, 1);
let fNOP = function() { };
let fBound = function() { let bindArgs = Array.prototype.slice.call(arguments); // 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值 // 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context return self.apply(thisinstanceof fNOP ? this : context, args.concat(bindArgs)); };
fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; };