1. Understanding JavaScript prototypes
Many programming languages have the concept of classes. We can compare prototypes and classes to see the differences and similarities between them.
1. Class: A class is an abstraction of a specific thing, so a class is an abstract thing. In object-oriented, classes can be used to construct objects. This is an abstract-concrete process. In real life, it's like building a car from drawings.
2. Prototype: Using prototypes to construct objects in JavaScript is a concrete-specific process. In real life, it's like a certain brand of car - another brand of car.
2. Set the prototype of the object
1. Object.create(proto[,propertiesObject])
proto an object as the prototype of a newly created object.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The result of running the above code is that ‘bensz’ is printed out.
2. Constructor
The constructor can set the prototype with the prototype attribute and use new to create the object.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
The above code can also print 'bensz'
Illustrated process:
There are actually three steps when using the new keyword to create a new object bensz. 1. Create a new object bensz 2. Set the _proto_ of bensz. This is the _proto_ attribute pointing to car.prototype. 3. Car.apply(bensz,[]), bensz performs the logo assignment operation on Car. At this time bensz The object has a logo attribute.
3. Prototype chain
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Process: 1. Create a Car constructor and set its prototype attribute. 2. Create a Bensz constructor whose prototype attribute is an object of Car type. At this time, since it is an object created with the new keyword, this object has a _proto_ attribute, which points to Car.prototype. 3. Create a bensz1 object because it is created with the new keyword. It also has a _proto_ attribute, which points to the prototype attribute of the constructor Bensz, that is, Bensz.prototype.
In addition, we can find that Car.prototype can be created using new Object. Because it is an object itself, it also has the _proto_ attribute and points to Object.prototype.
So the entire prototype chain is: 1. bensz1._proto_—— 2. Bensz.prototype(new Car('bensz')), Bensz.prototype._proto_—— 3. Car.prototype,Car.prototype._proto_—— 4. Object.prototype.
Access properties: First search on the own object, if not, search up along the prototype chain
Modify and delete attributes: Only the attributes of the object itself can be modified and deleted