Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze Js inheritance and prototype chain

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to analyze Js inheritance and prototype chain, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

Inheritance and prototype chain

When it comes to inheritance, JavaScript has only one structure: objects. Each instance object (object) has a private property (called proto) that points to the prototype object (prototype) of its constructor. The prototype object also has its own prototype object (proto), layer upon layer until the prototype object of an object is null. By definition, null does not have a prototype and serves as the last link in the prototype chain.

Almost all objects in JavaScript are instances of Object at the top of the prototype chain.

Inherit attribute

The JavaScript object is a dynamic property "package" (referring to its own properties). The JavaScript object has a chain pointing to a prototype object. When trying to access the properties of an object, it searches not only for the object's prototype, but also for the object's prototype and its prototype, searching up layer by layer until a name-matching property is found or the end of the prototype chain is reached.

Code example

Function fn () {this.a = 1; this.b = 2;} const o = new fn (); fn.prototype.b = 3 position fn.prototype.c = 4 undefined console.log (o.a); console.log (o.b); console.log (o.c); console.log (o.d); / / 1 undefined / 2 hand / 4 hand / undefined

An and b are their own properties of o and can return values directly.

Why do we set fn.prototype.b=3 and return 2? Because we return directly when we find that we have this property, and we won't look it up.

C is not an attribute of o, so it will look it up on o.prototype and find c and return the value directly.

D is not an attribute of o, so it will look for it on o.prototype, find it on o.protype.prototype, find it on o.protype.prototype, find it as null, stop searching and return undefined

Take a look at the print of o constructor

{a: 1 b: 2 _ proto__: b: 3 c: 4 constructor: "fn () _ proto__: constructor:" Object () hasOwnProperty: "hasOwnProperty () isPrototypeOf:" isPrototypeOf () propertyIsEnumerable: "propertyIsEnumerable () toLocaleString:" toLocaleString () toString: "toString" () valueOf: "valueOf () _ _ defineGetter__:" _ _ defineGetter__ () _ _ defineSetter__: "_ defineSetter__ () _ lookupGetter__:" _ lookupGetter__ () _ _ lookupSetter__: "_ lookupSetter__ () get _ _ proto__:" _ proto__ () Set _ _ proto__: inheritance _ _ proto__ ()} inheritance method

JavaScript does not have other "methods" defined by class-based languages. In JavaScript, any function can be added to an object as a property of the object. Function inheritance is no different from other property inheritance, including "property masking" above (which is equivalent to method overrides in other languages).

When an inherited function is called, this points to the currently inherited object, not the prototype object in which the inherited function resides.

Var o = {a: 2, m: function () {return this.a + 1;},}; console.log (o.m ()); / / 3 this' / when o.m is called, 'this' points to o.var p = Object.create (o); / / p is an object that inherits from o p.a = 4; / / creates p's own attribute' a'console.log (subscription ()). / / 5 this.a' / when calling JavaScript, 'this' points to p _ this' / and because p inherits the m function of o / / so, at this time,' CPA', that is, p's own attribute'a', is used in the prototype.

In JavaScript, functions (function) are allowed to have attributes. All functions have a special property-prototype. Is the prototype object of Object by default

Function doSomething () {} console.log (doSomething.prototype); / / regardless of how the function is declared, the function in / / JavaScript always has a default prototype property. Var doSomething = function () {}; console.log (doSomething.prototype)

In the JavaScript code block displayed on the console, we can see a default attribute of the doSomething function, prototype. After this code runs, the console should display a result similar to the following:

{constructor: "doSomething (), _ _ proto__: {constructor:" Object (), hasOwnProperty: "hasOwnProperty (), isPrototypeOf:" isPrototypeOf (), propertyIsEnumerable: "propertyIsEnumerable (), toLocaleString:" toLocaleString (), toString: "toString (), valueOf:" valueOf ()}} "

We can add new properties to the prototype object of the doSomething function, as follows:

Function doSomething () {} doSomething.prototype.foo = "bar"; console.log (doSomething.prototype)

You can see that the result after running is as follows:

{foo: "bar", constructor: "doSomething (), _ _ proto__: {constructor:" Object (), hasOwnProperty: "hasOwnProperty (), isPrototypeOf:" isPrototypeOf (), propertyIsEnumerable: "propertyIsEnumerable (), toLocaleString:" toLocaleString (), toString: "toString (), valueOf:" valueOf ()}} "

We can now create a doSomething instance based on this prototype object through the new operator.

Code:

Function doSomething () {} doSomething.prototype.foo = "bar"; / / add a property onto the prototypevar doSomeInstancing = new doSomething (); doSomeInstancing.prop = "some value"; / / add a property onto the objectconsole.log (doSomeInstancing)

The result of running is similar to the following statement.

{prop: "some value", _ _ proto__: {foo: "bar", constructor: "doSomething (), _ _ proto__: {constructor:" Object (), hasOwnProperty: "hasOwnProperty (), isPrototypeOf:" isPrototypeOf (), propertyIsEnumerable: "propertyIsEnumerable (), toLocaleString:" toLocaleString () ToString: toString (), valueOf: valueOf ()}

We can see that prop is an attribute of doSomeInstancing, and proto in doSomeInstancing is doSomething.prototype.

Let's print out the properties in it.

Console.log ("doSomeInstancing.prop:" + doSomeInstancing.prop); console.log ("doSomeInstancing.foo:" + doSomeInstancing.foo); console.log ("doSomething.prop:" + doSomething.prop); console.log ("doSomething.foo:" + doSomething.foo); console.log ("doSomething.prototype.prop:" + doSomething.prototype.prop); console.log ("doSomething.prototype.foo:" + doSomething.prototype.foo)

The results are as follows:

/ / doSomeInstancing's own property, directly return the value doSomeInstancing.prop: some value// is not the own property of doSomeInstancing. Look at the prototype object and find that this property directly returns the value doSomeInstancing.foo: bar// is not a property of the function itself, nor is it a property on the prototype object. Look up layer by layer, and finally find that when prototype is null, it indicates that there is no such attribute. So return undefineddoSomething.prop: undefineddoSomething.foo: undefineddoSomething.prototype.prop: undefined// to find that the doSomething prototype object has a foo attribute, so directly return the value doSomething.prototype.foo: bar performance

Finding attributes on the prototype chain is time-consuming and has side effects on performance, which is important in situations where performance requirements are demanding. In addition, the entire prototype chain is traversed when trying to access properties that do not exist.

When you traverse the properties of an object, each enumerable property on the prototype chain is enumerated. To check whether an object has a property of its own definition, rather than a property on its prototype chain, you must use the hasOwnProperty method that all objects inherit from Object.prototype. Here is a concrete example to illustrate it:

Console.log (doSomeInstancing.hasOwnProperty ("prop")); / / trueconsole.log (doSomeInstancing.hasOwnProperty ("bar")); / / falseconsole.log (doSomeInstancing.hasOwnProperty ("foo")); / / falseconsole.log (doSomeInstancing.__proto__.hasOwnProperty ("foo")); / / true

HasOwnProperty is the only method in JavaScript that handles attributes and does not traverse the prototype chain.

Another such method: Object.keys ()

Note: it is not possible to check if a property is undefined. This property may already exist, but its value happens to be set to undefined.

Attachment: prototype chain is the main method to realize inheritance

Let's talk about inheritance first. Many OO languages support two inheritance methods: interface inheritance and implementation inheritance.

|-API inheritance: only inherits method signatures

|-implement inheritance: inherit the actual method

Because the function does not have a signature, it is impossible to implement interface inheritance in ECMAScript. It only supports implementation inheritance, which mainly depends on the prototype chain.

The basic idea of prototype chain:

Use prototypes to make one reference type inherit the properties and methods of another reference type.

Each constructor has a prototype object, which contains a constructor to the constructor, while the instance object contains an internal pointer to the prototype object (_ _ proto__). If you make the prototype object equal to an instance of another type, the prototype object will contain a pointer to another prototype (_ _ proto__), and the other prototype will also contain a pointer to another constructor (constructor). If another prototype is an instance of another type... This constitutes the chain of examples and prototypes.

Basic ideas of prototype chain (illustration):

After reading the above, do you have any further understanding of how to analyze Js inheritance and prototype chain? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report