bind用于改變this指向
Function.prototype.myBind = function(obj, ...args) {
var self = this
var fn = function() {
var _this = this instanceof self ? this : obj
return self.apply(_this, args.concat([...arguments]))
}
fn.prototype = this.prototype
return fn
}
測試一下
function foo(name) {
this.name = name
}
var obj = {}
//上下文 功能 done
var bar = foo.myBind(obj)
bar("jack")
console.log(obj.name) //'jack'
// 參數(shù) 功能 done
var tar = foo.myBind(obj, "rose")
tar()
console.log(obj.name) //'rose'
// new 功能 error
var alice = new bar("alice")
console.log(obj.name) //alice obj name should be 'jack'
console.log(alice.name)