//ECMAScript 5 Function.prototype.bind函數相容處理
//ECMAScript 5 Function.prototype.bind函數相容處理
//ECMAScript 5 Function.prototype.bind函數相容於處理
//ECMAScript 5 Function.prototype.bind函數相容處理
//ECMAScript 5 字> (function(){
if ( !Function.prototype.bind ) { //function(){}.bind
Function.prototype.bind = function ( o, /*參數清單*/ ) {
var self = this, boundArgs = Array.prototype.slice.call(arguments, 0);
return function(){
var args = [], i;
for ( i = 1; i for ( i = 0; i return this. apply(o, args);
}
}
}
})();
1、簡單呼叫範例
複製程式碼
程式碼如下:
/*example 1*/
function f1(y, z ){ return this.x y z;}
//呼叫1
var g1 = f1.bind({x:1}, 2); //this.x = 1; y = 2;
console .loog( g1(3) ); //this.x y 3 = 6;
//呼叫2
var g2 = f1.bind({x:1}); //this.x = 1;
console.log( g2(2,3) ); //this.x 2 3 = 6
2、DOM呼叫範例
複製程式碼
程式碼如下:, eleText = document.getElementById("text");
eleBtn.onclick = function(color) { color = color ||Btn.onclick = function(color) { color = color ||Btn.onclick = function(color) { color = color ||Btn.on. "; this.style.color = color; //此時的this指向eleText }.bind(eleText, "#cd0000");