Function.prototype.bind用法示例
更新時間:2013年09月16日 10:16:45 作者:
想必大家對Function.prototype.bind并不陌生吧,下面為大家介紹下它的簡單調(diào)用及DOM調(diào)用,感興趣的朋友可以參考下
復制代碼 代碼如下:
//ECMAScript 5 Function.prototype.bind函數(shù)兼容處理
(function(){
if ( !Function.prototype.bind ) { //function(){}.bind
Function.prototype.bind = function ( o, /*參數(shù)列表*/ ) {
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、簡單調(diào)用示例
復制代碼 代碼如下:
/*example 1*/
function f1(y, z){ return this.x + y + z;}
//調(diào)用 1
var g1 = f1.bind({x:1}, 2); //this.x = 1; y = 2;
console.loog( g1(3) ); //this.x + y + 3 = 6;
//調(diào)用 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; }
//調(diào)用
var g3 = f2.bind(null, 1); //x = 1
console.log( g3(2) ); //x + 2 = 3
2、DOM調(diào)用示例
復制代碼 代碼如下:
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");
您可能感興趣的文章:
- 讓IE8瀏覽器支持function.bind()方法
- ie支持function.bind()方法實現(xiàn)代碼
- javascript中的Function.prototye.bind
- 深入理解JS中的Function.prototype.bind()方法
- jQuery中的.bind()、.live()和.delegate()之間區(qū)別分析
- JQuery中綁定事件(bind())和移除事件(unbind())
- JQuery中Bind()事件用法分析
- jQuery事件綁定on()、bind()與delegate() 方法詳解
- 淺談javascript中call()、apply()、bind()的用法
- 關于Function中的bind()示例詳解
相關文章
Javascript 計算字符串在localStorage中所占字節(jié)數(shù)
本文給大家分享的是使用Javascript 計算字符串在localStorage中所占字節(jié)數(shù),分別對UTF-8和UTF-16兩種編碼進行了詳細說明,有需要的小伙伴可以參考下。2015-10-10解決layui中的form表單與button的點擊事件沖突問題
今天小編就為大家分享一篇解決layui中的form表單與button的點擊事件沖突問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08