Anonymous Anonymous - 1 month ago 9
Javascript Question

how to inherit javascript anonymous functions assigned to variables?

Trying to understand inheritnace in javascript and totally confused

I just need that DogCat to have

bark
and
meow
function and able to access
this
(somehow) of each object in inheritance chain:

var cat = function() { this.name = "tom"; this.cat_instance = this; }
var dog = function() { this.name = "bob"; this.dog_instance = this; console.log("cat is here!");}

cat.prototype.meow = function() { console.log("mhew"); }
dog.prototype.bark = function() { console.log("whoof"); }

var DogCat = function() {
DogCat.prototype = dog.prototype;
DogCat.constructor = cat;
console.log("my name is " + this.dog_instance + " " + this.cat_instance);
}


So
DogCat.prototype
now (should ?) point to
dog
prototype and in instance of
DogCat
I should able to get at least
bark
function but instance doesn't have this function.

Okay thats a mess (in my mind), I am try now apply both inherited constructors to a child:

var DogCat = function() {
cat.apply(this);
dog.apply(this);
console.log("my name is " + this.dog_instance + " " + this.cat_instance);
}


Then, point a prototype to a dog:

DogCat.prototype = dog.prototype;
var d = new DogCat();
> cat is here!
>my name is [object Object] [object Object]


Now I can access the
bark
but how to deal with
meow
function? How to build prototype chains properly?

UPD

sorry in
DogCat
there should be
DogCat.prototype = dog.prototype
, fixed

Answer

You are mostly on the right track but have some mistakes.

Your first code will not work because you assign the prototype inside the constructor, that means the prototype is assigned after the object is created. First created object wouldn't have the prototype methods but second one would. Also you already noticed assigning the constructor won't do any good. You have to apply constructors manually.

var DogCat = function() {
    cat.apply(this);
    dog.apply(this);
    console.log("my name is " + this.dog_instance + " " + this.cat_instance);
    }
DogCat.prototype = dog.prototype;

Prototypes are also just normal objects. No magical properties. You can't assign two prototypes and expect it to work magically. If you want to inherit from two base classes, you can write an inherit function for your convenience.

function inheritFrom(myClass,base){
    for(var prop in base.prototype){
        myClass.prototype[prop] = base.prototype[prop];
    }
}

// Use it like:
inheritFrom(DogCat, dog);
inheritFrom(DogCat, cat);

Or manually assign all the methods you need from base classes if you know what you are inheriting.

DogCat.prototype.bark = dog.prototype.bark;
DogCat.prototype.meow = cat.prototype.meow;
Comments