bind函數:給對象綁定方法。

bind是Function的方法,js5版的,在js3中能夠用代替方案模擬,但依舊有些細節無法模擬。 app


/*******************************
 *bind函數在IE8中沒有,兼容性代碼:js權威指南(6th)P191
 ********************************/
if (!Function.prototype.bind) {
	Function.prototype.bind = function (o/*, args*/) {
		if (typeof this !== "function") {
			// closest thing possible to the ECMAScript 5 internal IsCallable function 
			throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); 
		}
		
		var self=this, boundArgs=arguments;
		return function(){
			var args=[],i;
			for(i=1; i<boundArgs.length; i++) args.push(boundArgs[i]);
			for(i=0; i<arguments.length; i++) args.push(arguments[i]);
		
			return self.apply(o, args);
		};
	}; 
} 

 /*******************************
 *bind函數在IE8中沒有,兼容性代碼:js權威指南(6th)P191 end
 ********************************/





 /******************************* 函數

 *bind函數在IE8中沒有,兼容性代碼:某博客版 this

*(http://www.jb51.net/article/32837.htm) spa

 ********************************/ .net

if (!Function.prototype.bind) { prototype

Function.prototype.bind = function (oThis) { code

if (typeof this !== "function") { htm

// closest thing possible to the ECMAScript 5 internal IsCallable function  對象

throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");  繼承

}

var aArgs = Array.prototype.slice.call(arguments, 1),

fToBind = this,  fNOP = function () {}, 

fBound = function (){ 

return fToBind.apply(this instanceof fNOP && oThis?this:oThis, 

aArgs.concat(Array.prototype.slice.call(arguments))); 

};

fNOP.prototype = this.prototype; 

fBound.prototype = new fNOP(); 

return fBound; 

}; 

 /*******************************

 *bind函數在IE8兼容性代碼:某博客版。結束

 ********************************/


-------------------------------------------------------------------

具體用法

-------------------------------------------------------------------



o1對象有個f方法

想讓o2對象繼承o1的f方法

bind一下,o2對象就有這個現成的東西了。


//o2.f = o1.f.bind(o2);


//簡練的bind寫法1:

var f=function(x, y){ return (x+y);}

var o={};

g=f.bind(o,1);//綁定1到x;

alert(  g(2)  );





//簡練的bind寫法2:

//把f函數綁定到o上,並返回一個新方法:f.bind(o);

function f(x,y){        return  x+y;    }

var o={};

//var g=f.bind(o, 1); alert( 'g 是: '+ g(3)  );

//或者

 o.m=f.bind(o, 2); alert(  o.m(10)  );

//_________________________________





//把o1的f方法綁定到o2上,並返回一個新方法:o2.f = o1.f.bind(o2);

var o1={x:1, y:3};

o1.f = function(y){

return (this.x + this.y); }

var o2={x:50, y:8};

o2.y=8;

 

o2.f =o1.f.bind(  o2 );//把o1.f綁定爲o2.f

alert(  o2.f()  );



var g=o1.f.bind(  o2 );//把f綁定到o2上並返回爲一個新函數

alert(  g()  );

相關文章
相關標籤/搜索