In order to solve the problem of the prototype, we need to create the object by combining construction methods and prototypes, define the properties in the constructor method, and define the method in the prototype . This effective aggregation of the advantages of both, is currently the most commonly used in a way.
functionPerson (name,age,friends) {//property is defined in the constructor This. Name =name; This. Age =Age ; This. Friends =friends;} Person.prototype={Constructor:person,//method is defined in the prototypeSayfunction() {alert ( This. name+ "[" + This. friends+ "]"); }}//This is where the properties are stored in their own space.varP1 =NewPerson ("Leon", 23,["Ada", "Chris"]);p 1.name= "John";p 1.friends.push ("Mike");//added a friend to P1.P1.say ();//John ["Ada", "Chris", "Mike"]varP2 =NewPerson ("Ada", 33,["Leon"]);p 2.say ();//Ada Leon
The memory model diagram looks like this:
The creation of JavaScript objects is based on the construction method + prototype mode