I’m learning javascript and was going through an example here:
https://developer.mozilla.org/en/A_re-introduction_to_JavaScript
function personFullName() {
return this.first + ' ' + this.last;
}
function personFullNameReversed() {
return this.last + ', ' + this.first;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
this.fullNameReversed = personFullNameReversed;
}
var x = new Person('mickey', 'mouse');
document.write(x.fullName());
Why are the lines of code
this.fullName = personFullName;
this.fullNameReversed = personFullNameReversed;
instead of
this.fullName = personFullName();
this.fullNameReversed = personFullNameReversed();
I thought we’re setting this.fullName based on the return value of personFullName()
That code is making the “fullName” and “fullNameReversed” properties be functions, not simple properties.
Thus when you want the full name you’d write
x.fullName();Functions are objects in JavaScript and can be the value of variables and properties. This is a feature that makes JavaScript surprisingly powerful.