bind()方法创建并返回一个新的函数,当被调用时,将其this设为bind()的第一个参数。
自己实现一个bind()
1.因为bind方法不会立即执行函数,需要返回一个待执行的函数(这里用到闭包,可以返回一个函数)return function(){}
2.作用域绑定,可以使用apply或者call方法来实现
3.参数传递,需要用apply或call传递数组
this.value = 2
var foo = {
value: 1
};
var bar = function(name, age, school) {
console.log(name) // 'An'
console.log(age) // 22
console.log(school) // '家里蹲大学'
console.log(this.value) // 1
}
Function.prototype.bind = function(newThis) {
var args = Array.prototype.slice.call(arguments, 1) //拿到除了newThis之外的预置参数序列
var that = this
return function() {
return that.apply(newThis, args.concat(Array.prototype.slice.call(arguments)))
//绑定this同时将调用时传递的序列和预置序列进行合并,合并后才是返回函数的完整参数。
}
}
var result = bar.bind(foo, 'An')
result(22, '家里蹲大学')