1. bind方法
- 函數(shù)調(diào)用bind方法, 可以指定函數(shù)內(nèi)部的this, 并把bind函數(shù)的第一個(gè)參數(shù)之后的參數(shù)拼接到返回的新函數(shù)的實(shí)參之前.
- 示例
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. 實(shí)現(xiàn)一個(gè)自己的bind方法
Function.prototype._bind = function(obj) {
if(typeof this !== 'function') {
throw new Error("只有函數(shù)才能調(diào)用bind方法")
}
let that = this
// 去掉arguments的第一項(xiàng)
let args = Array.prototype.slice.call(arguments,1)
return function() {
// 去掉arguments第一項(xiàng)
arguments = [].splice.call(arguments,1)
args = args.concat(arguments)
that.apply(obj,args)
}
}