1. The origin of prototype inheritance:
Crockford introduced a method of implementing inheritance. This method does not use a constructor in the strict sense. Instead, it uses prototypes to create new objects based on existing objects without having to create custom types.
The functions given are as follows:
function Object(o){
// 临时性的构造函数
function F() {}
F.prototype = o;
return new F();
}
Explanation:
(1) Inside the object function, a temporary constructor is created first, and then the passed-in object is used as the prototype of the constructor. (2) The last returns a new instance of this temporary type.
(3) In essence, object() performs a shallow copy of the object passed in.
2. Prototype inheritance:
Examples are as follows:
function Object(o){
// 临时性的构造函数
function F() {}
F.prototype = o;
return new F();
}
var person = {
name:"萝卜头",
friends:["1","2","3"]
};
var anotherPerson = Object(person);
anotherPerson.name="大萝卜头";
anotherPerson.friends.push("5");
var anotherPerson2 = Object(person);
anotherPerson2.name="萝卜干";
anotherPerson2.friends.push("7");
console.log(person.friends);
Code explanation:
In this example, the person object that can be used as the basis for another object is passed to the Object function, and then the function returns a new object. This new object will have person as the prototype, so its prototype contains a basic type value attribute and a reference type value attribute. person.friends is not only owned by person but also shared by anotherPerson and anotherPerson2.
Note: This kind of prototypal inheritance requires you to have an object that can be used as the basis of another object . If there is such an object, you can pass it to the object() function and then add one modification to the obtained object according to specific needs. can.
3. Improvement:
ES5 standardizes prototypal inheritance through the new Object.create() method. This method accepts two parameters: an object used as the prototype of the new object and an object defining additional properties for the new object.
var person = {
name:"萝卜头",
friends:["1","2","3"]
};
var anotherPerson = Object.create(person,{
name:{
value:"大萝卜头"
}
});
anotherPerson.friends.push("5");
var anotherPerson2 = Object.create(person,{
name:{
value:"萝卜干"
}
});
anotherPerson2.friends.push("7");
console.log(person.friends);
Prototype inheritance is a good choice when you just want one object to be similar to another. But properties that contain reference type values will always share the desired value, just like using the prototype pattern.
Note: For information, refer to "JavaScript Advanced Programming"