I've been playing with JS and I'm trying to assign a new variable inside an object method but I keep getting hit with undefined in the console.
This is the object I created:
const rodrigo = {
firstName: 'Rodrigo',
lastName: 'Pinto',
job: 'Programmer',
birthYEar: '1997',
friends: ['Michael', 'Scott', 'Jim'],
hasDriversLicense: true,
calcAge: function () {
this.age = 2021 - this.birthYEar;
return this.age; //We don't actually need to return anything here actually, because we already said that age = calculation.
}
But when I try to log rodrigo.age it returns undefined. Could someone walk me through this? I'm not understanding what I'm doing wrong.
CodePudding user response:
Your object doesn't initially have an age
property assigned to it. To be able to access age
you need to execute the calcAge
function via rodrigo.calcAge()
first.
CodePudding user response:
If you want rodrigo.age
to return something, you'll have to define that property. But since you defined calcAge
instead, and never call that method, there is no age
property (yet).
One solution is to replace calcAge
with a getter function named age
. The advantage is then that you can read rogrigo.age
and implicitly invoke that function:
const rodrigo = {
firstName: 'Rodrigo',
lastName: 'Pinto',
job: 'Programmer',
birthYear: '1997',
friends: ['Michael', 'Scott', 'Jim'],
hasDriversLicense: true,
get age() {
return new Date().getFullYear() - this.birthYear;
}
}
console.log(rodrigo.age);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Side note: the calculation of age is a bit more complex than this -- you need to know someone's full birthdate and compare it with the current month and date to see whether it already passed.
CodePudding user response:
const rodrigo = {
firstName: 'Rodrigo',
lastName: 'Pinto',
job: 'Programmer',
birthYEar: '1997',
friends: ['Michael', 'Scott', 'Jim'],
hasDriversLicense: true,
calcAge: function () {
this.age = 2021 - this.birthYEar;
console.log(this.age);
return this.age;
}
}
rodrigo.calcAge();
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
In JavaScript there are different ways to define a user-defined object types. In your case I will recommend to use a constructor function. So just follow the idea of the snippet below.
function Rodrigo() {
this.firstName = 'Rodrigo';
this.lastName = 'Pinto';
this.job = 'Programmer';
this.birthYEar = '1997';
this.friends = ['Michael', 'Scott', 'Jim'];
this.hasDriversLicense = true;
this.calcAge = function () {
this.age = 2021 - this.birthYEar;
return this.age;
};
this.calcAge();
}
console.log((new Rodrigo()).age);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>