Reputation: 41
I'm trying to understand the use of "this". I can't get the age from the function calculation(undefined). What am I doing wrong?
const reina= {
firstName: 'Reina',
birthYear: 1998,
location:'Tokyo',
friends:['Chihomi','Lei','Louis'],
calcAge: function(){
this.age= 2021 - this.birthYear;
return this.age;
}
}
console.log(reina.age);
output:
undefined
Upvotes: 1
Views: 40
Reputation: 7591
For the sake of reusability, I would use a Class instead of assigning to an object. That would leave less code in the long run.
this
points to the current scope you're in, whether your in a method, an object or a class.
To create a class, you need to add a constructor, that you can send in parameters to. As you can see in the code, this
in the constructor means the class Person
when I call calcAge()
.
I also added new Date().getFullYear()
which should be self-explanatory.
class Person {
constructor(firstName, birthYear, location, friends) {
this.firstName = firstName;
this.birthYear = birthYear;
this.location = location;
this.friends = friends;
this.age = this.calcAge(birthYear);
}
calcAge(birthYear) {
return new Date().getFullYear() - birthYear;
}
}
const reina = new Person('Reina', 1998, 'Tokyo', ['Chihomi', 'Lei', 'Louis']);
const rickard = new Person('Rickard', 1890, 'Stockholm', ['Beatrice', 'Gretchen', 'Hans']);
console.log(reina.firstName, reina.age);
console.log(rickard.firstName, rickard.age);
Upvotes: 0
Reputation: 89374
You never called the calcAge
function.
const reina = {
firstName: 'Reina',
birthYear: 1998,
location: 'Tokyo',
friends: ['Chihomi', 'Lei', 'Louis'],
calcAge: function() {
this.age = 2021 - this.birthYear;
return this.age;
}
}
console.log(reina.calcAge());
console.log(reina.age);
It seems like a getter is most appropriate in this case.
const reina = {
firstName: 'Reina',
birthYear: 1998,
location: 'Tokyo',
friends: ['Chihomi', 'Lei', 'Louis'],
get age() {
return 2021 - this.birthYear;
}
}
console.log(reina.age);
Upvotes: 2