JS中的bind()方法

Function.prototype.bind()方法

bind()方法主要就是將函數綁定到某個對象,bind()會創建一個函數,函數體內的this對象的值會被綁定到傳入bind()第一個參數的值,例如,f.bind(obj),實際上可以理解爲obj.f(),這時,f函數體內的this自然指向的是obj

例子

var a = {
	b : function(){
		var func = function(){
			console.log(this.c);
		}
		func();
	},
	c : 'Hello!'
}
a.b();
//undefined
注意:這裏的this指向的是全局作用域,所以會返回undefined

var a = {
	b : function(){
		var that = this;
		var func = function(){
			console.log(that.c);
		}
		func();
	},
	c : 'Hello!'
}
a.b();
//Hello!
注意:可以通過賦值的方式將this賦值給that

var a = {
	b : function(){
		var func = function(){
			console.log(this.c);
		}.bind(this);
		func();
	},
	c : 'Hello!'
}
a.b();
//Hello!

var a = {
	b : function(){
		var func = function(){
			console.log(this.c);
		}
		func.bind(this)();
	},
	c : 'Hello!'
}
a.b();
//Hello!
注意:當然,也可以通過bind的方式綁定this,上述兩種bind綁定的方式都可以

再看另外一種用法

例子

function f(y, z){
	return this.x + y + z;
}
var m = f.bind({x : 1}, 2);
console.log(m(3));
//6
注意:這裏bind方法會把它的第一個實參綁定給f函數體內的this,所以這裏的this即指向{x : 1}對象,從第二個參數起,會依次傳遞給原始函數,這裏的第二個參數2,即是f函數的y參數,最後調用m(3)的時候,這裏的3便是最後一個參數z了,所以執行結果爲1 + 2 + 3 = 6

分步處理參數的過程其實是一個典型的函數柯里化的過程(Curry)


我們再來看一道題目

var a = document.write;
a('hello');
//Error

a.bind(document)('hello');
//hello

a.call(document, 'hello');
//hello
注意:這裏直接調用a的話,this指向的是global或window對象,所以會報錯,通過bind或者call的方式綁定this至document對象,即可正常調用

可以用bind的方式預定義參數,例子

function list(){
	return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3);
//[1, 2, 3]

//預定義參數
var a = list.bind(undefined, 10);

var list2 = a();
//[10]

var list3 = a(1, 2, 3);
//[10, 1, 2, 3]
注意:這裏的Array.prototype.slice.call(arguments)是用來將參數由類數組轉換爲真正的數組,a的第一個參數undefined表示this的指向,第二個參數10即表示list中真正的第一個參數,依次類推


如何自己實現bind方法?

因爲bind()函數發佈在ES5中,因此並不能很好的在所有瀏覽器中運行,需要Polyfill,當然現在幾乎所有現代瀏覽器都支持ES5

//my_bind方法支持綁定對象
Function.prototype.my_bind = function(context){
	var self = this;
	return function(){
		return self.apply(context, arguments);
	}
}

//測試
function a(){
	return this.name;
}
a();	//''

var b = {name : 'kong'};
a.bind(b)();	//kong

a.my_bind(b)();		//kong
上述是最簡單的一種實現方式,僅可用來綁定,不可傳參

更加健壯的方式:

//my_bind方法不僅可以綁定對象,還可以傳參
Function.prototype.my_bind = function(context){
	var args = Array.prototype.slice.call(arguments, 1);
	//args [7, 8]
	var self = this;
	return function(){
		var innerArgs = Array.prototype.slice.call(arguments);
		//innerArgs [9]
		var finalArgs = args.concat(innerArgs);
		//finalArgs [7, 8, 9]
		return self.apply(context, finalArgs);
	}
}

//測試
function a(m, n, o){
	return this.name + ' ' + m + ' ' + n + ' ' + o;
}

var b = {name : 'kong'};

a.my_bind(b, 7, 8)(9);		//kong 7 8 9

注意:這裏my_bind函數中args表示的是在bind時傳入的預定義參數,這裏即爲7和8,分別表示m和n,return中的innerArgs表示的是調用a的時候傳入的參數,這裏表示9,即o,最後用concat連接兩個數組,即爲finalArgs,所以最後執行的是a(7, 8, 9),this指向b,實現了一個完善點的bind方法


處理bind返回的函數如果作爲構造函數,搭配new關鍵字出現的話,我們綁定的this就需要被忽略的兼容性問題

更加完美的方式

//bind返回的函數如果作爲構造函數,搭配new關鍵字出現的話,我們綁定的this就需要被忽略
//處理構造函數場景下的兼容
Function.prototype.bind = Function.prototype.bind || function(context){
	//確保調用bind方法的一定要是一個函數
	if(typeof this !== "function"){
		throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
	}
	var args = Array.prototype.slice.call(arguments, 1);
	var self = this;
	var F = function(){};
	F.prototype = this.prototype;
	var bound = function(){
		var innerArgs = Array.prototype.slice.call(arguments);
		var finalArgs = args.concat(innerArgs);
		return self.apply(this instanceof F ? this : context || this, finalArgs);
	}
	bound.prototype = new F();
	return bound;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章