Reputation: 16142
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()
Upvotes: 1
Views: 62
Reputation: 25081
personFullName
returns the function itself (like a pointer).
personFullName()
returns the results of the function.
This allows the Person
object to have a method that returns the full name, as opposed to a property. If I use this object like x.first = newVal
, the fullName
method re-calculates the full name.
If it were a property, I would have to use it like ''x.first = newVal; x.fullName = newFullName;'.
Hope this helps.
Upvotes: 1
Reputation: 83356
this.fullName = personFullName;
Creates a method called fullName
, and assigns it the function declared as personFullName
If you were to do
this.fullName = personFullName();
that would create an object property called fullName
that held the value that personFullName()
produced at that particular moment when invoked.
Upvotes: 1
Reputation: 413737
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.
Upvotes: 3