I am a beginner in JS and have been trying to get the following code to work but it is not giving me the expected results:
cat = function(name) {
this.name = name;
this.talk = function() {
alert("Cat "+name+" says meow.");
}
}
cat1 = new cat("George");
cat1.talk();
cat.prototype.changeName = function(name) {
this.name = name;
}
cat2 = new cat("Felix");
cat2.changeName("Bill");
cat2.talk();
From what I read about JS, from the second alert I should get "Bill says meow". But looks like the property is not getting set and I am still getting "Felix says meow."
Can anybody point out the mistake? It will be really helpful. Thanks in advance.
It’s not a matter of inheritance, it’s a matter of accessing the right variables. Take a look at your constructor:
Specifically
alert("Cat "+name+" says meow.");.namewill always refer to the argument you passed to the constructor. You should accessthis.nameinstead, since yourchangeNamemethod setsthis.nameto a new value.There is no reason to define this method inside the constructor though, add it to the prototype as well: