Demo 1:
function Person () { this. Name = ' Hjzgg '; this. Age =; This function () { + "" + Age ); } } var New Person (); P.show ();
Error: Neither name nor age is defined.
Demo 2:
function Person () { this. Name = ' Hjzgg '; this. Age =; This function () { alert (this-age); } } var New Person (); P.show ();
That's right.
Demo 3:
function Person () { this. Name = ' Hjzgg '; this. Age =; This function () { alert (this-age); } } var New Person (); P.show.call ({});
Error: Name and age are undefined.
Demo 4:
function Person () { this. Name = ' Hjzgg '; this. Age =; var = this; This function () { + "" + Self.age); } } var New Person (); P.show.call ({});
Through var = this, correct.
Demo 5:
function Person () { thisfunction() { alert (' Hello world! ' ); } This function () { SayHello (); } } var New Person (); P.show ();
Error: SayHello not defined.
Demo 6:
function Person () { varfunction() { alert (' Hello world! ') ); } This function () { SayHello (); } } var New Person (); P.show ();
That's right.
Conclusion:
Each function has its own this object, which is bound at run time based on the execution environment of the function, that is, in the global object, this point is the Window object, and in the custom function, the This object points to the object that called the function, that is, This refers to the object that invokes the execution environment. In the case of a function nesting environment, this refers to an object that invokes an external function or an internal function's execution environment.
Then there may be a new question: Why are self.name and self.age right?
In fact, this involves another topic: instance members and local members . The point of creating a constructor is to use it to create an instance, so all members belonging to the instance need to be defined with this, and only those members that are not part of the instance will not be defined with this; Of course, after the method is defined with this, the method is called You need to add this.
Demo 7:
var person = { ' hjzgg ', +, function() { alert ( age ); } } Person.show ();
Error: Name and age are undefined.
Demo 8:
var person = { ' hjzgg ', +, function() { alert ( this. age);} } Person.show ();
That's right.
Demo 9:
var person = { ' hjzgg ', +, function() { alert ( this. age);} } Person.show.call ({});
Error: Name and age are undefined.
Demo 10:
var person = { ' hjzgg ', +, function() { alert ( Person + "" + person , age); } } Person.show.call ({});
That's right.
JS self = explanation of this