[Solve a problem every day series-0001] Javascript Apply and call comparison

Source: Internet
Author: User

Same point:

    • Each function contains these two native methods
    • The effect of both of them is the same, for executing functions under a specific scope, essentially setting the value of this object within the function.

Different points:

    • The parameter types passed in are different. Apply (function scope, array[parameter]), call (function scope, parameter 1, parameter 2, Parameter 3 ...). Note: The function scope parameter does not pass or NULL, the default is window, and in strict mode is undefined, which is an invalid scope.

Application Scenarios:

    • The most important function of these two functions is to expand the scope of function to run, the advantage is that the object does not need to have any coupling relationship with the method, with "borrow chicken eggs" to describe the most appropriate.
    • Example
      Window.color = "Red"; var o = (color:oblue); function Saycolor () {alert (this.color); Saycolor ();//redøaycolor.ca11 (TBIs) ; REDØAYCOLOR.CA11 (window); Redøaycolor.call (o); Blue

        

Add:

    • A method bind () is also defined in ECMAScript 5, which creates an instance of a function whose this value is bound to the value passed to the bind () function.
    • Example
      Window.color = "Red"; var o = (color: "Blue" ); function Saycolor () {alert (this. color); var Objectsaycolor = Saycolor.bind (o);
      Objectsaycolor ();///Blue

      Browsers that support the bind () method are ie9+, firefox4+, Safari 5.1+, Opera 12+, and Chrome.

Reference:

    • Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

[Solve a problem every day series-0001] Javascript Apply and call comparison

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.