In JavaScript, when you access an object's own properties through its methods, you must use the This.fieldname method.
The reason is that the function in JavaScript is stateless, and when you access an object's properties, you must specify the current context state, which is to add the This keyword. If not specified, the context defaults to window.
Examples are as follows:
1 var obj =2 {3 Name: "James",4 showname: function() {5 alert (name); 6 }7 }
Executes the obj.showname () output through the console as an empty string.
Cause: Obj.showname () executes alert (name); When the statement does not specify a context for name, it defaults to Window.name, and the value of Window.name is "", so output an empty string.
1 var obj =2 {3 Name: "James",4 showname: function() {5 alert (this. Name); 6 }7 }
Change: Alert (this.name);
Execute the Obj.showname () output through the console as "James".
The behavior is consistent when the following definitions are used.
1 function Obj () {2 this. Name= "James"; 3 }4 obj.prototype.showname=function() {5 Alert (this. Name); 6 }7 varnew Obj ();
How objects in JavaScript access their properties