0

So i have a couple of objects and I'm confused as to why 'this' "sort of" works.

So I have a base class:

 var Dog = function(){      
      this.breed = "unknown";
      this.tailLength = 5;      
      this.stats = {};
      this.born = function() {
    console.log(this.breed +" was born!");
      };
      this.init = function (generatedstats) {
    this.stats = generatedstats
      };
      return this;
  };

And I have a class 'labrador' that inherits the dog class:

 var Labrador= function () {
        Dog.apply(this, arguments); //inheritance
        this.likes = "retrieving toys!";
    this.breed = "Labrador";
    this.stats.friendlyness = this.stats.friendlyness + 4;
    this.tailLength = 8;
        return this;
    };

    NodeEntity.prototype = new Dog(); //inheritance

So thats my Labrador class.

and its all pulled together via an init module:

 for (i = 0; i < data.length; i++) {
            var dog = new Doggy(); //this is actually the Labrador class
                dog.init(data);
                Doggies.push(dog);
                dog.born();
            }

So the problem I'm having is, if I change something in the base class that -was not- set during init. It changes it for all things of type Dog.

Let me give an example, If in the above I changed "this.stats" in the Labrador class, thats fine, it only affects the labrador But, if i change this.tailLength in the Labrador class it changes it in the Dog class, and as a result affects all other classes that inherit the dog class

I guess I'd like to know what causes this and what i could do to fix it!

Jay
  • 1,033
  • 1
  • 18
  • 31
  • 2
    It needs to be `Dog.apply(this, arguments)` and `Labrador.prototype = Object.create(Dog.prototype); //inheritance` – Bergi Aug 19 '15 at 10:55
  • 1
    What sort of inheritance is `Dog (this, arguments); //inheritance` supposed to be? – connexo Aug 19 '15 at 10:56
  • EDIT: I missed out the apply, Already had that, and new object(); and Object.create(object.proto) are the same – Jay Aug 19 '15 at 10:58
  • I meant to put apply in I must of missed it out – Jay Aug 19 '15 at 10:58
  • 1
    see duplicate answer ... the important part is that you missed `Labrador.prototype.constructur = Labrador;` right after `Labrador.prototype = new Dog();`. In your case you are overwriting the Labrador constructor with the Dog constructor, hence that specific behaviour – devnull69 Aug 19 '15 at 11:10

0 Answers0