javascript prototype

Problems with constructors

The method in the constructor, every time an object is created, the object will recreate this method once, and each object has an exclusive method. However, the content of this method is exactly the same, so resources are wasted.

Solution 1:

Extract the method in the constructor, put it outside the constructor, and perform reference assignment inside the constructor.

Then the created object will point to the function outside the constructor to achieve the purpose of sharing.

The accompanying problems: the increase of global variables, resulting in global variable pollution, chaotic code structure, and not easy to maintain.

Workaround 2:

Use prototypes.

what is a prototype

When the constructor is created, the system will create and associate an object by default. This object is the prototype, and the prototype object is an empty object by default.

The default prototype object will have a constructor property pointing to the constructor.

The role of prototypes

The members of the prototype object are shared by all objects created using its associated constructor.

Use of prototype objects

1. Use the dynamic properties of the object to add members to the prototype object.

2. Directly replace the prototype object.

Note: Replacing the prototype object directly will cause the prototype of the object created before the replacement to be different from the prototype of the object created after the replacement.

Replacing Prototype Notes:

In the newly replaced prototype, there is no constructor attribute, which will affect the rationality of the triangular (constructor, prototype, object) structural relationship. Therefore, in the newly replaced prototype, manually add the constructor attribute to ensure the rationality of the relationship. The assignment is associated constructor.

Notes on using prototypes

1. When using an object to access a property, it will first look in the object, if found, it will be used directly, and if not found, it will be searched in the prototype.

2. When using an object to set properties, it will only be searched in the object itself, not in the prototype. If this property is not found in the object itself, add a new property to the object. If there is this property in the object, Modify this property.

3. If there is a reference type property in the prototype object, when the content of the property is modified by the object, all other objects related to the prototype object will be affected.

4. In general, properties are not added to the prototype object, only the methods that need to be shared are added to the prototype object.

1. This property is not a standard property, so there is a general problem.

2. This property is generally not recommended.

3. This property can be used when debugging.

4. This property is a property in the prototype.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325071915&siteId=291194637
Recommended