Copy Code code as follows:
ECMAScript 5 Function.prototype.bind function compatible processing
(function () {
if (! Function.prototype.bind) {//function () {}.bind
Function.prototype.bind = function (o,/* parameter list * * *) {
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);
}
}
}
})();
Usage examples:
1. Simple Call Example
Copy Code code as follows:
/*example 1*/
function F1 (y, z) {return this.x + y + z;}
Call 1
var G1 = F1.bind ({x:1}, 2); this.x = 1; y = 2;
Console.loog (G1 (3)); This.x + y + 3 = 6;
Call 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;}
Call
var g3 = F2.bind (null, 1); x = 1
Console.log (G3 (2)); X + 2 = 3
2. Dom Call Example
Copy Code code as follows:
var elebtn = document.getElementById ("button")
, Eletext = document.getElementById ("text");
Elebtn.onclick = function (color) {
color = Color | | "#003399";
This.style.color = color; This points to Eletext
}.bind (Eletext, "#cd0000");