Home >Web Front-end >JS Tutorial >js Prototype attribute explanation and common methods_Basic knowledge
Function: Prototype
Each constructor has an attribute called prototype (prototype, which will not be translated below, use its original text). This attribute is very useful for declaring common variables or functions for a specific class.
Definition of prototype
You don’t need to explicitly declare a prototype attribute because it exists in every constructor. You can take a look at the following example:
Example PT1
Add attributes to prototype
As you can see above, prototype is an object, therefore, you can add properties to it. Properties you add to the prototype will become common properties to objects created using this constructor.
For example, I have a data type Fish below, and I want all fish to have these attributes: livesIn="water" and price=20; in order to achieve this, I can add those attributes to the prototype of the constructor Fish.
Example PT2
Let’s make some fish next:
Let’s take a look at the attributes of fish:
The output should be:
You see that all fish have properties livesIn and price, we don’t even declare these properties specifically for each different fish. This is because when an object is created, this constructor will assign its attribute prototype to the internal attribute __proto__ of the new object. This __proto__ is used by this object to find its properties.
You can also add common functions to all objects through prototype. This has the advantage that you don't need to create and initialize this function every time you construct an object. To explain this, let's revisit Example DT9 and rewrite it using prototype:
Use prototype to add functions to objects
Example PT3
We can create objects as usual:
Copy code
Copy code
Here is a diagram to illustrate how the prototype works. Each instance of this object (boss1, boss2, boss3) has an internal property called __proto__, which points to the prototype property of its constructor (Employee). When you execute getSalary or addSalary, this object will find and execute this code in its __proto__. Note this: there is no duplication of code here (compare with the diagram in Example DT8).