This also raises the issue of why bother using a function if general objects can return a value?
The reason is fairly obvious but deserves some thought.
Functions Versus Objects
You do have a choice of associating a value with an object as in:
You also can define a function that does the same thing:
The difference is that the function has a natural way to accept arguments. For example, you can write:
but without defining it to be a function you can't write:
In other words, objects can simply represent a value or a state. That value or state can be manipulated by the methods that the object provides but it cannot be modified while it is being used in an expression.
A function, on the other hand, represents a relationship between input data and the result.
Notice also that, while a function is an object, not all objects are functions and in this sense a function is a "bigger" object.
When should you consider using a value associated with an object?
Some might reply "never" as it isn't a common pattern and could be confusing.
However, if an object represents data or something with state then it is a good approach.
var d=Date.now(); alert(d);
The toString function returns the number of milliseconds since the date epoch. A Date object is an ideal example of when to use an object as a value.
The jQuery approach to Ajax is built on the jqXHR object which wraps the XmlHttpRequest object that the browser provides. It isn't often that you need delve this deeply into jQuery Ajax, but when you [ ... ]
One of the interesting things about jQuery's approach to Ajax is that it can be extended in many ways. In the previous chapter we discovered that you can use converters to create your own data types, [ ... ]