I have the following code:
class Pet {
constructor(name) {
this.petName = name;
}
}
Pet.prototype.speak = {
name: function() {
console.log(this.petName);
}
};
// -----------------------------------------------
const myPet = new Pet("Max");
myPet.speak.name();
I expect this code to print Max, but instead it prints undefined.
If I change the console.log to console.log(this); it prints { name: [Function: name] }. Which makes me think that function doesn't have access to the instance properties.
How can I ensure that this function has access to the instance?
thisdoesn't refer to the object anymore but instead to the object the function is called in (in this case the object containing only the name() method)