When the constructor is called, a pointer to the original prototype is added to the instance, and we can add properties and methods to the prototype at any time, and can be reflected in the instance, but if the prototype object is re-created, it will cut off the connection of the constructor to the original prototype.
function Dog () { } varnew Dog (); ={ constructor:dog, "Bob", one, function () { alert ("Jump");} ; Friend.jump (); // Error
Here the prototype object is rewritten after the dog instance is created, so friend points to a prototype that does not contain a jump ().
There are many properties that can be shared, such as name, age, in the section where the overrides are made. When we modify the properties of one of the instances, the other instances are affected, which is not what we want. Therefore, the combination of constructors and prototype patterns is often used when creating.
The constructor pattern defines the instance properties, and the prototype schema defines methods and shared properties.
functionDog (name,age,breed) { This. Name =name; This. Age =Age ; This. Breed =breed; This. Friends = ["Ange", "Array"]; } Dog.prototype={constructor:dog, jump:function() {alert ("Jump," please.); } }; varDog1 =NewDog ("Bob", "5", "Shiba"); varDOG2 =NewDog ("Amy", "2", "Alaska"); Dog1.friends.push ("Edit"); Console.log (Dog1.friends); //["Ange", "Array", "Edit"]Console.log (Dog2.friends);//["Ange", "Array"]
JavaScript Advanced Programming Learning Notes (object-oriented programming) 2