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 ?
Mainly there are three types of inheritance in JavaScript. They are, prototypal, pseudo classical, and functional.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With