Function. prototype. bind usage example

Source: Internet
Author: User

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 ");

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.