用法
我們先來看個小例子
var age= 1;
var obj = {
age: 2,
say: functino () {
console.log(this.age)
}
}
obj.say(); // 1
obj.bind(window);
obj.say(); // 2
從上面的例子我們可以看出,bind 的作用就是爲了修改函數內部 this 的指向。如上面的例子中,經過 obj.bind(window) 之後,obj.say 函數中的 this 指向了 window
實現
我們來看一下自己怎麼實現這個bind函數
Function.prototype.bind = function (context) {
var self = this;
return function () {
self.apply(context, arguments)
}
}
利用 apply 函數,改變函數內部 this 指向。但是這個時候 bind 函數是沒法傳遞其他參數的,如果要傳遞其他函數,我們需要做一點改造
Function.prototype.bind = function () {
var self = this;
var context = Array.prototype.shift.call(arguments); // 拿到上下文對象
var args = Array.prototype.slice(arguments); // 拿到其他參數
return function () {
self.apply(context, Array.prototype.concat.call(args, Array.prototype.slice(arguments)))
}
}