1) Javascript object member experiment:
The existence of object members at the first breakpoint:
The existence of object members at the second breakpoint:
One sentence: Regarding js functions: this refers to the object at the nearest level outside the function, while this within the internal function of the nested function refers to the window object.
In one sentence: The oo features of js: use this. member method to define the members of an object. Using objects has the unique dynamic persistence of js. There are differences between classes and object instances, and .prototype. member definition is a classic way of definition. , classes and object instances are unified.
2) Javascript object shared member variable experiment:
Run to the first breakpoint:
The difference between simple variables and object variables
Use a member defined by .prototype. If the member is a simple variable, each object instance has its own copy. (Example: Man.prototype.noObejctVar)
Use a member defined by .prototype. If the member is an object variable, each object instance shares the same copy of the object. (Example: Man.prototype.ManGhost)
Why is there such a difference? There is no difference between the ManGhost variable and the noObjectVar variable. They are both members defined using .prototype. It’s just that their types are different, which means that the way they access and use them is different. It’s just that the ManGhost variable stores the new object, and the noObjectVar variable stores the value (or a reference to a certain value). In other words, ManGhost stores a reference to the object. The object can be operated through this reference, and the noObjectVar variable Memory storage can also be some kind of value reference, but this reference cannot be used to operate it.
Looking from another perspective
The noObjectVar variable stores a reference to a string object.
a.noObjectVar="new string a";
This means that noObjectVar points from the original string object reference to the new string object reference. (It can also be said that the new string object overwrites the original string object)
a.ManGhost=new Ghost("a");
b.ManGhost=new Ghost("b");
In this way, there is no problem of shared objects between a and b. However, there is another problem. It is a waste to define the new object when prototype.ManGhost. However, it is wrong to use .prototype in this way.
Using .prototype to define member functions and shared variables is the correct usage.
To use javascript to correctly define classes, please see: [Technical Memo] JavaScript to define class specifications