Inheritance as part of constructor. Is it possible?


#1


https://www.codecademy.com/en/courses/objects-ii/3/5?curriculum_id=506324b3a7dffd00020bf661


The lesson deals with adding inherited detail from parent classes. But it does not seem to be possible to declare inheritance inside a class' own constructor. See the comments marked "1)" & "2)" in the code below.


function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
}

// create your Emperor class here and make it inherit from Penguin
function Emperor(name) {
    this.name = name;
    //this.prototype = new Penguin(); // 1) Why does this line not work?
}

Emperor.prototype = new Penguin();  // 2) But this line does work!

// create an "emperor" object and print the number of legs it has

var emperor = new Emperor("Jeff");
console.log(emperor.numLegs);

Surely handling all inheritance settings of a class are best, neatly handled within its own constructor?


#2

@ocisly, about Object.prototype from MDN:

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype

So, Emperor.prototype = new Penguin(); always works.

function Emperor(name) {
this.name = name;
this.prototype = new Penguin(); // 1) Why does this line not work?
}

Why does this line not work? Because your Emperor doesn't have property numLengs. Try this code:

console.log(emperor.prototype.numLegs); // 2

I think, that when you used this.prototype = new Penguin();, you set a property prototype (name of this property can be another). To access to this property you have to write emperor.propName.numLengs.
The correct way inherit property numLengs is to use Object.prototype:

function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
}

//create your Emperor class here and make it inherit from Penguin
function Emperor(name) {
    this.name = name;
}

// OR you can create class in this way:
Emperor.prototype = new Penguin();

// create an "emperor" object and print the number of legs it has
var emperor = new Emperor("Emperor");
console.log( "name = " + emperor.name );
console.log( "numLengs = " + emperor.numLegs );

Result:

name = Emperor
numLengs = 2

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.