DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> Function.prototype.bind用法示例
Function.prototype.bind用法示例
編輯:關於JavaScript     
復制代碼 代碼如下:
//ECMAScript 5 Function.prototype.bind函數兼容處理
(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 < boundArgs.length; i++ ) args.push(boundArgs[i]);
for ( i = 0; i < arguments.length; i++ ) args.push(arguments[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

/*example 2*/
var f2(x, y){ return x + y; }
//調用
var g3 = f2.bind(null, 1); //x = 1
console.log( g3(2) ); //x + 2 = 3

2、DOM調用示例
復制代碼 代碼如下:
var eleBtn = document.getElementById("button")
, eleText = document.getElementById("text");

eleBtn.onclick = function(color) {
color = color || "#003399";
this.style.color = color; //此時的this指向eleText
}.bind(eleText, "#cd0000");
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved