Up the Food-I-mean-Prototype Chain, something for the prototype chain


#1


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


Well, my code runs fine and well but I had a question. If emperor inherits from penguin and penguin inherits from animal, does emperor inherit from animal?


Penguin.prototype = new Animal();
Emperor.prototype = new Penguin();


#2

Yes. All the way up the chain to Object. (null actually, since that is the real top of the prototype chain…)

There is a gotcha, though, which was touched on in a topic earlier this week. Will try to track it down so as not to repeat. In brief, if Animal() has its own defined properties that are passed in as parameters, they won’t pass down to the subclasses. Only those properties that are defined as literals in the parent class are inherited.

numLegs = 2;

in the Penguin class will be inherited by Emperor class instances. If numLegs was passed as an argument to Animal(), then it is not inherited. Penguin and Emperor must define their own properties.

This is where private class variables come in. Every object instance of any subclass will inherit the property.

I’ll dig around for that other example and we can build upon it.

Update

Easier than I thought…

Private variables and methods

Applying it to this discussion:

Code
// https://discuss.codecademy.com/t/private-variables-and-methods/46690
// study by Roy

function Foo(bar) {
    var foobar = "private";
    this.bar = bar;
    this.fooprivate = function() {
        return foobar;
    };
}

newfoo = new Foo("bar");

console.log(newfoo.bar);           // bar
console.log(newfoo.foobar);        // undefined
console.log(newfoo.fooprivate());  // private

function Bar(foo) {
    this.foosy = true;
    this.foo = foo;
}

Bar.prototype = new Foo();

newbar = new Bar("foo");

console.log(newbar.foo);           // foo
console.log(newbar.bar);           // undefined
console.log(newbar.foobar);        // undefined
console.log(newbar.fooprivate());  // private

function FooBar(foobar) {
    this.foobar = foobar;
}

FooBar.prototype = new Bar();

newfoobar = new FooBar("Golly, gee...");
console.log(newfoobar.foo);           // undefined
console.log(newfoobar.bar);           // undefined
console.log(newfoobar.foobar);        // Golly, gee...
console.log(newfoobar.fooprivate());  // private
console.log(newfoobar.foosy);         // true

#3

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