Hi!
I was trying to see if I could change the value and something that I didn’t expect happened. The first console.log was expected, but then I added a property with the same name as the function, so that the object return this value when I call (is that the correct term?) the property and starts to return a TypeError when trying to call the function inside the object.
Since I added a property with the same name as the function, I can’t get the function’s value? And how to avoid this?
function Bird() {
let hatchedEgg = 10;
this.getHatchedEggCount = function() {
return hatchedEgg;
};
}
let ducky = new Bird();
ducky.getHatchedEggCount();
console.log(ducky.getHatchedEggCount()); // 10
ducky.getHatchedEggCount = 15;
console.log(ducky.getHatchedEggCount); // 15
console.log(ducky.hatchedEgg); // undefined
console.log(ducky.getHatchedEggCount()); // TypeError: ducky.getHatchedEggCount is not a function
ducky.hatchedEgg = 5;
console.log(ducky.hatchedEgg); // 5
console.log(ducky.getHatchedEggCount); // 15
console.log(ducky.getHatchedEggCount()); // TypeError: ducky.getHatchedEggCount is not a function
I moved your question to its own topic because you were asking a question related to your own code for a challenge and were not answering the OP of the other thread. It is always best to create your own thread for you specific question(s). Also, it is advisable to use the Ask for Help button on the challenge, so it auto-populates with your current code and the challenge url.
Thanks for your response.
Sorry. I thought it would be better to put it there because it was related. And I thought that avoiding creating a new topic would be preferable, but, in fact, the way I did it gets very confusing.
Thanks.
Last thing. Is it possible to prevent this from happening?
I tried to change ‘let’ to ‘const’, const hatchedEgg = 10;, but it didn’t work.
Anyway, thank you very much.
You might also use a class with getters and setters. That should also afford you some internal control over the API. Although having a setter named getHatchedEggCount wouldn’t be a good idea.
class Bird {
constructor(value) {
this.hatchedEgg = value;
}
get getHatchedEggCount() {
return this.hatchedEgg;
}
set getHatchedEggCount(value) {
this.hatchedEgg = value;
}
}
const bird = new Bird(10);
console.log(bird.getHatchedEggCount); // 10
bird.getHatchedEggCount = 20; // 20
console.log(bird.getHatchedEggCount); // 20
A method is a function assigned to a property on an object. If you overwrite the property with a different value you will not have access to the function.
I’m not really sure why you would want to use the same property like that anyway (intentionally), especially when the property holds a function that is supposed to be reusable code. But if it’s intentional and not done by accident you can also save the method out to a temp variable and restore it again later.