The Apply () and call () methods of the Function object

Source: Internet
Author: User

Each function contains two non-inherited methods: Apply () and call (). The purpose of both methods is to invoke the function in a specific scope, and the specific scope is the object specified by the This parameter.

The really powerful place for apply () and call () is the ability to extend the scope in which functions are run. Let's look at an example:

 Window.color = "Red" ;  var  o = {color: "Blue"  function   Saycolor () {alert ( this  .color);}                      Saycolor ();  //  red  Saycolor.call (this ); //            red  saycolor.call (window); //                 red  saycolor.call (o); //  blue  

Saycolor () is defined as a global function, and when it is called in the global scope, it does display "red"-because the evaluation of This.color is converted to window.color evaluation. Saycolor.call (this) and saycolor.call (window) are two ways to explicitly call a function in the global scope, and the results will of course show "Red".

However, when you run Saycolor.call (o), the execution environment of the function is different, because the this object in the function body points to O, and the result shows "blue".

The biggest benefit of using call () or apply () to extend the scope is that the object does not need to have any coupling with the method.

The Apply () and call () methods of the Function object

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.