SoFunction
Updated on 2025-03-01

Comprehensive understanding of inheritance in JavaScript (must-read)

In JavaScript, we can use prototypes to achieve inheritance.

For example

function baz(){
="";
}

function foo(){

}
=new baz();
var myFoo=new foo();
;

In this way, we can access the attribute oo in baz. This is not possible in actual use, because of the sharing characteristics of the prototype (data is saved on the heap),

All instances use a prototype, but once the baz attribute has a reference type, it will be tragic. If one instance is modified, the other instance will change as well...wuwuwu

There will naturally be combination inheritance

function baz(){
="";
}
=function(){

}

function foo(){
(this);//The second call}
=new baz();//The first callvar myFoo=new foo();
;
;

This will have a problem, and the code also shows that baz will be called twice. How can Virgo allow it?

If you add a sentence, will the second method not need to have the problem with the first method? The answer is no.

The reason is that the search for attributes starts with the object itself. Only when it is not found will it be found in the prototype. When calling, the attributes are inherited.

Let me add another sentence, then won’t it be enough to just use call inheritance like this? This is feasible if you don’t use a prototype, but how can you not use a prototype as a Virgo?

The method is shared on the prototype, so the performance is much better.

Parasitic combination inheritance

__extends=function (p,c){
function ctor(){
=c;//Assignment constructor}
=;
=new ctor();
}

function baz(){
=[1];
}
=function(){

}
__extends(baz,foo);
function foo(){
(this);
}
var myFoo=new foo();
;
;

This not only solves the problem of two calls, but also solves the fact that when the object calls the constructor, the real function that creates the object is called instead of other constructors on the prototype chain.

There is a statement in the code.

The constructor is an attribute on the prototype object and is the creator of the object. Since our prototype attributes are reassigned, the constructor is inherited.

Here I want to talk about how objects are created, that is, what new has done.

For example:

var a=new b();

Actually, it is like this, a={}; creates a for a, and then (a); initializes a in the call. There is another step before the call, which is the internal prototype object of a.

The prototype object to which the prototype property set to b points. There is a constructor attribute on the prototype, which is used to create object allocation memory controls.

It's probably all... It's still late, let's break it. Keep a calm mind and don't be impatient. Work hard to change tomorrow, and hope everything will gradually get better.

The above is all the content that the editor brings to you about comprehensive understanding of inheritance (must-read) in JavaScript. I hope everyone will support Footstep Home more.