JavaScript method invocation pattern and function invocation pattern

Source: Internet
Author: User

This two-day reading of the JavaScript language of the essence of the 4th chapter on the function of several modes of thinking about half a day.

Here's the method call pattern followed by the function invocation pattern.


Method invocation Pattern:

When a function is saved as a property of an object, we call it a method. When a method is called, this is bound to the object. If the invocation expression contains an action that extracts a property (A.name or A[name]), then he is called as a method.

 1  var  myObject = { 2  value:1,  3  double : function  () {// double is a method of MyObject object  4  this . Value = this.value*2 5  }  6  };  7  myObject. double  (); // 2  

Function call Pattern:

When a function is not a property of an object, then he is called as a function:

Note at this point that when a function is called in this mode, this is bound to the global object.

1 varMyObject = {2Value:13 };4MyObject.Double=function () {5     varHelper =function() {//Helper is not a property of an object, so this is a pointer to a Global object window6          This. Value = This. value*2;7     }8 Helper ();9 } ;TenMyObject.Double();//the value of 1,value does not change

We can define a variable for the method double and assign the value to this, then the intrinsic function can access this by that variable. By convention, we name that variable:

1 varMyObject = {2Value:13 };4MyObject.Double=function () {5     varthat = This;//define the variable that, and assign it a value of this6     varHelper =function () {7That.value = that.value*2;8     }9 Helper ();Ten } OneMyObject.Double();//2, because of the indirect access to the This,value eventually changed

JavaScript method invocation pattern and function invocation pattern

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.