I'm working through CodeAcademy JS excercises and have a question about this example:
//Animal class
function Animal(name) {
this.name = name;
}
//Attach sayName method to Animal class
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
//create an animal object instance
var dog = new Animal('Barker');
//invoke a method attached to the prototype from the object instance
dog.sayName();
My understanding of this code is:
- JS creates a new Animal object instance that var dog points to as a result of the use of the new keyword before the call to function
Animal()- a function constructor - The prototype of the var dog object has the
sayName()method attached to it in the line:Animal.prototype.sayName = function() - Because
sayName()was attached to the classprototype, the method is now available to any objects created from theAnimalclass through use of thenew Animal()function constructor
Is this a correct understanding of what is happening with this code?
Also, I'm trying to understand how this points to the Animal object in this.name:
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
Doesn't Animal.prototype point to an actual object: the prototype object of this Animal object instance? If so, shouldn't this in this.name point to Animal.prototype, since sayName() is actually being invoked from Animal.prototype?
My understanding of the context for this is that this always points to the object that invokes the function. However, in this case, when dog.sayName() is invoked, this points to Animal, which is how this.name equals 'Barker' when it is logged to the console.
I'm guessing that either I am misunderstanding that Animal.prototype points to a prototype object, or that JS is doing something "behind the scenes" to associate dog.sayName() to this in the context of attaching a method to the prototype.
Multiple questions here in this little example, but getting a grasp on exactly what is happening here will really help my understanding of these fundamental concepts.
doghave full access to the functions and properties ofAnimal.prototype. You may have a look at qr.ae/RO44Vn for a good read about thethisof JS.