I made a mistake with the age property on these objects and when I try to reassign different values later, it won't change it at all.
I want this to work with the Object.create
Method. What should I do to fix this?
var personProto = {
calculateAge: function() {
console.log(2019 - this.yearOfBirth)
},
fullName: function() {
console.log(this.name + ' ' + this.lastName)
}
}
var sam = Object.create(personProto, {
name: { value: "samuel" },
yearOfBirth: { value: 1092 },
lastName: { value: "max" },
job: { value: "developer" }
});
sam.yearOfBirth = 1992;
sam.calculateAge(); // 927
console.log(sam.calculateAge());
is giving me 927 assuming yearsOfBirth is still 1092 even if I changed it to 1992 and the output was supposed to be 27.
To change the value of an existing property of an object, specify the object name followed by: a dot, the name of the property you wish to change, an equals sign, and the new value you wish to assign.
Using the same method, an object's property can be modified by assigning a new value to an existing property. At this point, if we call the object, we will see all of our additions and modifications. Through assignment operation, we can modify the properties and methods of a JavaScript object.
By default, properties assigned using Object.create
are not writable. Attempting to write to a non-writable property is a silent error in JavaScript - one of many reasons to use Strict Mode.
Here is your code again, but in Strict Mode:
'use strict';
var personProto = {
calculateAge:function(){
console.log(2019 -this.yearOfBirth)
},
fullName:function(){
console.log(this.name + ' ' + this.lastName)
}
}
var sam = Object.create(personProto, {
name:{value:'samuel'},
yearOfBirth:{value:1092},
lastName:{value:'max'},
job:{value:'developer'}
});
sam.yearOfBirth = 1992;
console.log(sam.calculateAge());
927
Notice that it now fires an error and tells you exactly what's wrong.
To fix this, just make the properties writable.
'use strict';
var personProto = {
calculateAge:function(){
console.log(2019 -this.yearOfBirth)
},
fullName:function(){
console.log(this.name + ' ' + this.lastName)
}
}
var sam = Object.create(personProto, {
name:{value:'samuel',writable:true},
yearOfBirth:{value:1092,writable:true},
lastName:{value:'max',writable:true},
job:{value:'developer',writable:true}
});
sam.yearOfBirth = 1992;
console.log(sam.calculateAge());
927
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With