Context objects proficient in Javascript

Source: Internet
Author: User

Understanding context objects is the basis for understanding JS object-oriented. The context object is represented by this variable, which always points to the currentCodeIn the object, the global variable is actually the property of the window object. Let's look at a simple example of context object operations:

//************************************** ***************** // Use a function in the context object and switch its context object to another variable //** **************************************** * ************** var OBJ = {yes: function () {This. val = true ;}, No: function () {This. val = false ;}}; // at this time, the alert (obj. val = NULL); // After the Yes function is executed, the Val variable is associated with the OBJ object. yes (); alert (obj. val = true); // We set window. no points to OBJ. no and execute window. no = obj. no; window. no (); // obj. the value of Val has not changed, and the value of Val is false in window. // because of window. the context of no execution is window alert (obj. val = true); alert (window. val = false );

But when we switch the context object of obj. No to window, the Code becomes hard to understand. JS provides the call and apply methods to implement this function. In the above Code, we set window. No = obj. No; window. No ();
Replace it with obj. No. Call (window); or obj. No. Apply (window); the same result is returned.

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.