(Sorry for my bad English)
I am new to JS and currently on the Object/method part!
I've just written this pieces of code:
var jason = {
fname: 'jason',
lname: 'roy',
yearBorn: 2001,
CalcAge: function () {
this.age = 2020 - this.yearBorn;
}
};
jason.CalcAge();
console.log(jason.age);
The expected result on console log is 19 and that's exactly what I'm getting! But that's not my question.
My question is what is the point of going through such a long process just to create an age property?
AS you can, to print out the "age: 19" we first need to write:
jason.CalcAge();
And then,
console.log(jason.age);
Dont you guys think its kinda useless?
Like, I'm pretty sure you can simply create an age property and write function there to do the same thing as we're doing here but by doing an extra step of calling a function and then console logging the property it generates.
Once again, sorry for my bad English and let me know if you guys didn't get me!
jason.age = 2020 - jason.yearBorn;instead of calling the method, or you might have dropped the.ageproperty completely and just writtenconsole.log(2020 - jason.yearBorn). However, the standard approach would be probably be to give the object agetAge()method that can be called andreturns the calculated age instead of assigning it to a property.