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