Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript class inheritance and name of all inheritances?

I have a inheritance chain that goes like Starship -> Capital -> Omega and i would like to to be able to retrieve "Omega" from an object of class Omega.

function Starship(){
}


function Capital(){
    Starship.call(this);
}
Capital.prototype = Object.create(Starship.prototype);


function Omega(){
    Capital.call(this);
}
Omega.prototype = Object.create(Capital.prototype);

var omega = new Omega();


omega instanceof Omega // true
omega instanceof Capital// true
omega instanceof Starship // true    
omega.constructor.name // Starship

Is there a way to retrieve the youngest class that omega is part of, i.e. "Omega" or should i just add something like this.type = "Omega" to the Omega function ?

like image 654
user431806 Avatar asked Sep 02 '16 20:09

user431806


People also ask

How many types of inheritance are there in JavaScript?

Mainly there are three types of inheritance in JavaScript. They are, prototypal, pseudo classical, and functional.

What is JavaScript class inheritance?

Inheritance enables you to define a class that takes all the functionality from a parent class and allows you to add more. Using class inheritance, a class can inherit all the methods and properties of another class. Inheritance is a useful feature that allows code reusability.

What is inheritance in JavaScript with example?

By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.

How can I get multiple inheritance in JavaScript?

JavaScript does not support multiple inheritance. Inheritance of property values occurs at run time by JavaScript searching the prototype chain of an object to find a value. Since every object has a single associated prototype, it cannot dynamically inherit from more than one prototype chain.


1 Answers

The constructor property of a prototype object is writable. A quick test shows that changing its value does not change the non-enumerable nature of the property.

So you can change prototype objects' constructor properties to show the youngest constructor used:

    // ...

Capital.prototype = Object.create(Starship.prototype);
Capital.prototype.constructor = Capital;

    // ...

Omega.prototype = Object.create(Capital.prototype);
Omega.prototype.constructor = Omega;

    // ...

new Omega().constructor.name;  // is now "Omega"

Whether this is preferable to defining an object type property on the prototype, instead of changing the constructor value, is a matter of choice and opinion. The question is which of the two options you think would be more maintainable.

like image 84
traktor Avatar answered Nov 30 '22 04:11

traktor