This is my code example. I have a dog that with printAge()
function that log the age
property. age
has also gave as public property.
let Dog = function(){
};
Dog.prototype = function(){
let age = 3;
let printAge = function(){
console.log(age);
};
return{
age : age,
printAge : printAge
}
}();
Then I assign age
from dog's instance and call printAge()
to log but the value of age
3 is not updated with new value.
let DogInstance = new Dog();
DogInstance.age = 7;
DogInstace.printAge();
The result log is 3
But if I declare another function to assign the age
instead of assinging age
directly, it works.
Dog.prototype = function(){
let age = 3;
let setAge = function(val){
age = val;
}
let getAge = function() {
return age;
}
let printAge = function(){
console.log(age);
};
return{
setAge : setAge,
printAge : printAge
}
}();
let DogInstance = new Dog();
DogInstance.setAge(7);
DogInstace.printAge();
The result is: 7
Is that mean, we can't assign a property even if it was public in Revealing Prototype Pattern?
Aucun commentaire:
Enregistrer un commentaire