同时也会有一些与原生bind有出入的地方,详见上面的网址。
Function.prototype.bind = function(targetObj, ...args1) {
if (typeof this !== 'function') throw ("函数才能bind")
var ctx = this //原函数
//用于判断 是否被 new 调用
var fNOP = function() {}
fNOP.prototype = ctx.prototype
var fBound = function(...args2) {
// 如果 判断成立,则表示这个函数是在 new调用的,因为new操作会改变this
return ctx.apply(this instanceof fNOP ? this : targetObj, args1.concat(args2))
}
fBound.prototype = new fNOP() //拿到原型
//或者 fBound.prototype = Object.create(ctx.prototype)
return fBound
}