Prototypes and Prototype Chains

 

If you add properties and methods directly to the object in the constructor, it will cause each object to contain its own properties and methods, which will waste a lot of storage space when a large number of objects are created. By adding properties and methods to the prototype of the constructor, objects created through the constructor can share these properties and methods. That is, the prototype realizes the sharing of properties and methods .

Specify a prototype for the constructor:

ObjFunc.prototype = object.create(baseFunc)

ObjFunc.prototype.constructor = baseFunc

ES6 supports the class and extends keywords, so there is no need to use the above method (but the essence is still the same).

 

When accessing the properties and methods of an object, the JS runtime will first look for the properties and methods to be used in the object itself, and call it if it is found; if it is not found, it will look in the prototype. So the properties and methods in the prototype are shared, but they have a lower priority.

 

When the JS runtime looks for callable properties and methods, it does not only look for a layer of prototypes, because the prototype itself is also an object, so the JS runtime also looks for the prototype of the prototype object, until it finds the prototype of the Object. This forms a chain structure called a prototype chain. An inheritance -like effect can be formed through the prototype chain .

But inheritance in JS is different from inheritance in other programming languages! In other programming languages, the object of any class is composed of an instance, and the property value has only one value, no matter how many layers of inheritance. The inheritance formed by JS through the prototype chain is a chain composed of multiple instances, and the attribute value can also have multiple values ​​(each layer of the prototype can have a different value). The more, the more value!

The JS prototype chain is also used in Angular to construct the scope chain.

Guess you like

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