Function.prototype.myBind = function(thisArg) {
if (typeof this !== 'function') {
return
}
var _self = this
var args = Array.prototype.slice.call(arguments, 1)
var fnNop = function() {} // 定义一个空函数
var fnBound = function() {
// 检测new
// 如果当前函数的this指向的是构造函数中的this,则判定为new操作
var _this = this instanceof _self ? this : thisArg
return _self.apply(_this, args.concat(Array.prototype.slice.call(arguments)))
}
// 维护原型关系
if (this.prototype) {
fnNop.prototype = this.prototype
}
fnBound.prototype = new fnNop()
return fnBound
}
按照目前的方式基本实现手写bind,但是并非完美。每个函数都有个length属性,函数的length属性用于表示函数形参个数。更重要的是,函数的length属性值是不可重写的。该方式实现的话,length值会始终为零。