I have two JS functions doing the same thing:
1)
var person = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: function() {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
2)
var person = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: () => {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
Notice that the only difference between the two pieces of code is how the age() function is described. As I understand, the former is using a function statement and the latter is using a function expression.
The issue is however, that only the former piece of code returns the expected data, whereas the latter returns the following error:
Uncaught TypeError: Cannot read property 'getFullYear' of undefined
at Object.age
I am trying to understand why one works and the other doesn't when both are syntactically correct?
I've just started out learning JS in depth so detailed yet straight-forward answers would be appreciated. Thank you.