In-depth analysis on prototype of ctipt PT: Is prototype attributes a copy, a reference, or a fixed search method?
---- 02 _ add prototype attributes
//
<SCRIPT type = "text/JavaScript"> var person = function () {}; person. prototype. username = "zhangsan"; var person1 = new person (); var person2 = new person (); alert ("after the instance is created, person1.username:" + person1.username ); alert ("after the instance is created, person2.username:" + person2.username); alert ("before adding attribute age to the prototype, person1.age:" + person1.age ); alert ("before adding property age to the prototype, person2.age:" + person2.age); // Add property person to the prototype. prototype. age = new string ("18"); alert ("after adding attribute age to the prototype, person1.age:" + person1.age); alert ("after adding attribute age to the prototype, person2.age: "+ person2.age); </SCRIPT>
//
Output:
After the instance is created, person1.username: zhangsan
After the instance is created, person2.username: zhangsan
Before adding the property age to the prototype, person1.age: Undefined
Before adding the property age to the prototype, person2.age: Undefined
After adding the property age to the prototype, person1.age: 18
After adding the property age to the prototype, person2.age: 18
Q: Why do two instances, person1 and person2, add the corresponding attributes after adding attributes to the prototype?
Assume 1 copy: N instances are created with copies of the prototype attributes. After the age attribute is added to the prototype, the age attribute is added to N instances, and the value is the same as that of the prototype (copy)
-- N operations are required, which is unlikely!
Suppose 2 reference: N instances are created with the reference of the prototype property, add the age property to the prototype, and then add the age property (reference) to N instances. At this time, person. prototype. age and person. age references the same object string ("18 ")
-- N operations are required, which is unlikely!
Suppose 3 fixed search methods:
N instances are not created with the same prototype name. For example, when a person is created, it does not have the username attribute! After the age attribute is added to the prototype, N instances do not have the age attribute. when accessing person1.age, because it does not have the age attribute, you can search for it in a fixed way:
Because person1 is an instance of person (person1 instanceof person gets true), find person. prototype. if the property of age is not found, continue to the previous prototype search. Here, the JS engine finds the person. prototype. age attribute, so output!
-- You only need to modify prototype and search by fixed search method. This example can be interpreted!
Return full text