1. bind方法
- 函数调用bind方法, 可以指定函数内部的this, 并把bind函数的第一个参数之后的参数拼接到返回的新函数的实参之前.
- 示例
var obj = {a: 1}
function fn(a,b,c,d,e,f) {
console.log(this)
console.log(a,b,c,d,e,f)
}
var newFn = fn.bind(obj,1,2,3)
newFn(4,5,6)
[object Object] {
a: 1
}
1
2
3
4
5
6
2. 实现一个自己的bind方法
Function.prototype._bind = function(obj) {
if(typeof this !== 'function') {
throw new Error("只有函数才能调用bind方法")
}
let that = this
// 去掉arguments的第一项
let args = Array.prototype.slice.call(arguments,1)
return function() {
// 去掉arguments第一项
arguments = [].splice.call(arguments,1)
args = args.concat(arguments)
that.apply(obj,args)
}
}