1

If we have a parent object like:

var Animal = function(name) {
    this.name = name;
    return this;
}

and we use prototype like:

Animal.prototype.Dog = function(){
    console.log(this.name);
}

this just works great. But what I am trying to achieve is to inherit the parent property in child object like

Animal.prototype.Child = {
    Dog : function(){
        console.log(this.name);
    }
}

How can we do this. I am trying to find it for two days. I've also tried:

Animal.prototype.Child = {
    that:this,
    Dog : function(){
        console.log(this.that.name);
    }
}

But here that contains the window object not the Animal. Also

Animal.prototype.Child = {
    Animal: new Animal('Puppy'),
    Dog : function(){
        console.log(this.Animal.name);
    }
}

is NOT an option here.

Moin Uddin
  • 75
  • 5
  • 1
    I really don't understand what you are trying to achieve with `Animal.prototype.Child = { Dog: .... }`. That's not what inheritance usually looks like. Have a look at http://stackoverflow.com/q/17392857/218196. – Felix Kling Jan 30 '14 at 06:33

1 Answers1

2

Your inheritance chain doesn't look right. You'd create two different constructors. Each constructor creates an object. The inheritance part is setting up the prototype chain and calling "super" within the children class. In other words, you'd do this:

// Constructor for animals
function Animal(name) {
  this.name = name;
  // no need to return this
  // as a constructor returns the instance
  // when using the `new` keyword
}

// Public methods of all animals
Animal.prototype.say = function(){
  // implement
};

// Constructor for dogs
function Dog(name) {
  // Call "super", inherit parent properties
  Animal.apply(this, arguments);
}

// Public methods of dogs
Dog.prototype.fetch = function(){
  // implement
};

// Setup prototype inheritance chain
// and save a reference to our constructor
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Even though your inheritance didn't look right, this is a common misconception:

Animal.prototype.Child = {
  that: this, //<---
  ...
}

this is the context of a function, and the value depends on how that function gets called. this in the code above is window; notice that there's no function.

In the code below, this is obj:

var obj = {
  prop: 'foo', 
  method: function() {
    return this.prop;
  }
};

obj.method();
//^ logs "foo" because we are using dot notation (`obj` is the receiver)

If we call the function without dot notation it won't work. Again, this depends only on how the function gets called. This won't work:

var fn = obj.method;
fn(); // won't work
fn.call(obj); //=> will work, we pass the context explicitly
elclanrs
  • 92,861
  • 21
  • 134
  • 171