0

could you please help me to solve this misconception about prototypal inheritance in JavaScript

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


Animal.prototype.speak = function() {
    console.log("My name is " + this.name);
};

Animal.sayMoo = function(){
console.log("Mooooo!");
};

var animal = new Animal('Monty');

animal.speak(); // My name is Monty
animal.sayMoo; // undefined

as far as I know any instance of an object has all it properties, and in this example animal (instance of Animal) only has what inside the constructor "this.name" and the method "speek()" but not "sayMoo" because I did not use ( Animal.protoype.sayMoo = ...

I think maybe animal or any instance only inherit what is inside the Animal.prototype

is that the right answer? if yes, why animal inherits what inside the constructor ? maybe all properties inside the constructor go automatically to the prototype, so it can be inherited by any instance?

I wish i Solve this

Faisal Julaidan
  • 388
  • 4
  • 16
  • 2
    An instance of `Animal` *inherits* the `prototype`, and in addition you're very explicitly setting `this.name`, where `this` is your new instance. So no, it doesn't "go to the prototype"; it very explicitly is a property of the object, because that's what you're setting. – deceze Aug 29 '16 at 13:10
  • ohhh! it does make sense now. thank a lot. Just to make sure so any property outside the prototype can not be inherited by any instance, right ? – Faisal Julaidan Aug 29 '16 at 13:20
  • ohhh! it does make sense now. thank a lot. Just to make sure so any property outside the prototype can not be inherited by any instance, right ? – Faisal Julaidan Aug 29 '16 at 13:21
  • Right, any property directly attached to an object is directly attached to that object and won't usually be inherited by anything. – deceze Aug 29 '16 at 13:26
  • (I'm saying "usually" because Javascript is very malleable, and the `prototype` is in fact also "just an object"… so things *can* be inherited in all sorts of ways if you pass them around…) – deceze Aug 29 '16 at 13:27

0 Answers0