What is meant by 'first class object'?
Solution 1:
To quote Wikipedia:
In computer science, a programming language is said to support first-class functions (or function literal) if it treats functions as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions.
This page also illustrates it beautifully:
Really, just like any other variable
- A function is an instance of the Object type
- A function can have properties and has a link back to its constructor method
- You can store the function in a variable
- You can pass the function as a parameter to another function
- You can return the function from a function
also read TrayMan's comment, interesting...
Solution 2:
The notion of "first-class functions" in a programming language was introduced by British computer scientist Christopher Strachey in the 1960s. The most famous formulation of this principle is probably in Structure and Interpretation of Computer Programs by Gerald Jay Sussman and Harry Abelson:
- They may be named by variables.
- They may be passed as arguments to procedures.
- They may be returned as the results of procedures.
- They may be included in data structures.
Basically, it means that you can do with functions everything that you can do with all other elements in the programming language. So, in the case of JavaScript, it means that everything you can do with an Integer, a String, an Array or any other kind of Object, you can also do with functions.
Solution 3:
More complete approval of Strachey-Sussman-Abelson's formulation. So if your language supports such a construct then you've got a function as a first-class language :)
var men = function (objectOfAdmiration) {
return objectOfAdmiration();
};
men.isSweetHeart = true;
var women = function (objectOfAdmiration) {
return objectOfAdmiration();
};
women.isSweetHeart = true;
var aliens = function (objectOfAdmiration) {
return objectOfAdmiration();
};
function like(obj){
if (obj.isSweetHeart) {
return function (){ return "Holy TRUE!"};
}
else {
return function (){ return "Holy CRAP!"};
}
}
alert("Men like women is " + men(like(women))); // -> "Holly TRUE!"
alert("Women like men is " + women(like(men))); // -> "Holly TRUE!"
alert("Men like aliens is " + men(like(aliens))); // -> "Holly CRAP!"
alert("Aliens like women is " + aliens(like(women))); // -> "Holly TRUE!" :)
//women(like(aliens)); // Who knows? Life is sometimes so unpredictable... :)
In short, anything is a first-class object if it acts in the language as a state manipulation sort of object or type of object. Simply something you can operate on and pass around statements and evaluate in expressions at the same time. Or even shorter: when you can think of a function as an object that can be additionally invoked.