I came across this snippet of code on the MDN(Mozilla Developer Network) tutorial for JavaScript(by the way, a wonderful read). MDN JavaScript Re-introduction
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;
}
What intrigued me is the way the functions are called. The typical (); is not used to make the function call in the Person function. Within the Person function, we see that :
this.fullName = personFullName;
is used instead of
this.fullName = personFullName();
Here, the 'personFullName' is used like a variable or a property rather than, what it truly is, a function. Could someone shed a light on why this is so?
2 Answers 2
The functions are not called when running the function Person, only a reference is passed around.
JavaScript has functions as first class citizens that means that functions are a object like everything else: They can have properties, they can be saved in a variable, they can be passed as a parameter etc.
This allows for some really expressive code, look at this:
function isEven(item) {
return item % 2 == 0;
}
alert([1, 2, 3, 4, 5, 6].filter(isEven));
First a function is created and saved in the variable called isEven, afterwards we pass the function to Array.filter, which in case will pass every element into that array and return an array containing only the elements that isEven returned true for.
1 Comment
JavaScript is a functional language, and functions are first-class values. They're just objects, and can hold custom properties like any other object. And references to them can be passed around freely, which allows lots of cool stuff (as you probably will learn later).
So what happens here is that the functions are indeed not called, they are referenced via the variables holding them and are assigned as properties to the instance (this).
Like in the first example where an object is used (makePerson), they now can be called as methods on each instance:
var s = new Person("Simon", "Willison");
s.fullName(); // Simon Willison
The accompanying text explains that as well:
Every time we create a person object we are creating two brand new function objects within it — wouldn't it be better if this code was shared?
[Now the code you cited is] better: we are creating the method functions only once, and assigning references to them inside the constructor.
alert('foo')in any function and see that it doesn't appear