Consider the following JavaScript object definition :
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
I know that if we want to use the object property(i.e. a function) we have to write the following code :
person.fullName();
As per my knowledge, JavaScript objects are containers for named values called properties or methods.
Also, I know that I can define the object properties like firstName, lastName, id as individual variables. Now, my question is can I also define the function "fullName" as a variable? If it is possible then how? and if not then why?
Thank You.
It is possible. Note that your code is equivalent to this code:
The important bit to see is that
function() { return this.firstName + " " + this.lastName; }(or rather, the result of evaluation of that string of code) is a value, just like5566is, and can be contained in a property, or a variable, or an array... just like5566can. The only difference is, one is a number, the other - a function.Besides the original example of a function stored in a property ("method"), here is an example of a functional value being stored in a variable:
Here it is in an array:
Here it is being passed as a parameter: