Function.prototype.bind使用的例子
复制代码代码如下所示:/ / ECMAscript 5 function.prototype.bind功能兼容处理
(函数({){)
如果(!函数。
function.prototype.bind =功能(O / * * / {参数列表)
VaR自=,= array.prototype.slice.call boundargs(参数0);
返回函数(){
var args = { },我;
为(i = 1;i < boundargs.length;i++)args.push(boundargs {我});
为(i = 0;i < arguments.length;i++)args.push(参数{我});
返回this.apply(O,args);
}
}
}
});
使用的例子:
1。简单的调用的例子
复制代码代码如下所示:
例1
函数f1(y,z){返回这个。
1
VaR G1 = f1.bind({ x:1 },2); / /本。x = 1;y = 2;
Console.loog(G1(3)); / /本。x + y + 3 = 6;
2
VaR f1.bind(G2 = { x:1 }); / / x = 1;
console.log(G2(2,3)); / /本。x + 2 + 3 = 6
例2
var(x,y){返回x y;}
调用
VaR G3 = f2.bind(null,1); / / x = 1
console.log(G3(2)); / / x + 2 = 3
2,DOM调用示例
复制代码代码如下所示:
无功elebtn = document.getelementbyid(按钮)
eletext = document.getelementbyid(文本);
elebtn.onclick =功能(彩色){
颜色=# 003399色| | ;
this.style.color =颜色; / /这在这个时间点eletext
}。绑定(eletext,# cd0000 );