JavaScript Jems - Objects with Values |
Written by Ian Elliot | |||||
Thursday, 23 May 2019 | |||||
Page 2 of 4
toStringYou may not need a separate booleanValueOf type function but you do need a separate string value function. The reason is that what an object should return may be fundamentally different when a string value is required. For example, if a string value is required the object may need to format a numeric value so that it can be displayed. The good news is that it is easy to set a separate default string value using the toString function. For example, let's add a toString function to the myObject object:
Now what do you think displays if you try:
The answer is the string "ten" because alert expects a string argument. Now what do you think you get if you write:
The answer is 11 because the addition requires a numeric value. It shouldn't come as a surprise to learn that you don't have to return a string from toString. JavaScript has no way of enforcing a return type, so in practice if you return some other type of value it will be converted to a string before being used. One of the most useful things that you can do with toString is to define something more useful than the default object:Object that you see when you use alert or the debugging console. You can define a toString function that provides some useful debug information, as in:
A singleton exampleTo implement the earlier example of an item object with properties name, tax, price as a singleton or object literal you would use: var item = { and to make price the default numeric property and name the default string property you would define two methods: valueOf: function(){ The complete object is: var item = { If you don't like or aren't familiar with this way of creating an object you can use: var item={}; Now if we set some values in the properties and try to use item in an expression you will find that the valueOf and toString are called as defined earlier: item.name = "widget"; The first alert has an arithmetic expression which expects item to be a numeric value so valueOf is called and the result is 0+10 i.e. 10. Notice that as alert expects a string value as its parameter JavaScript kindly converts numeric 10 into a string. In the second alert the item parameter is supposed to be a string and so toString is called which returns the name and so widget is displayed.
|
|||||
Last Updated ( Tuesday, 06 August 2019 ) |