Copy codeThe Code is as follows:
// ECMAScript 5 Function. prototype. bind Function compatibility 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 example:
1. Simple call example
Copy codeThe Code is 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 codeThe Code is as follows:
Var eleBtn = document. getElementById ("button ")
, EleText = document. getElementById ("text ");
EleBtn. onclick = function (color ){
Color = color | "#003399 ";
This. style. color = color; // at this time, this points to eleText
}. Bind (eleText, "# cd0000 ");