| Just JavaScript - The Object Expression |
| Written by Ian Elliot | ||||||||
| Thursday, 12 June 2014 | ||||||||
Page 4 of 4
RecapTo summarize:
Functions in expressionsAs well as objects you can also include function evaluations within an expression. For example
in this case the function can return a general object and the valueOf and toString methods are used as described earlier to obtain a primitive value of the correct sort. For example if myFunction returns a custom object then its valueOf method is called to obtain a primitive value etc.. What is interesting is that as a Function object is an Object it too can define valueOf and toString methods. So for example:
Now you can write
and the result is 2 or
and the result is 4. You could also put a function evaluation in the valueOf method so that the function can be called with or without () and parameters.
Now writing myFunction() returns the same as writing myFunction. The object expression principleNow that we have all of the fine detail of how object expressions work, it is time to state the key principle of using expressions in JavaScript - the Object Expression Principle: Anywhere you can use an object you can use an expression At this point you might be thinking that this is not particularly useful as expressions evaluate to primitive values - Number, String or Boolean. However, as you can use a function in an expression, a single function evaluation is also an expression and in this case the return value can be any object. This one simple idea makes it possible to do a lot of things that would otherwise be very difficult. For example when you are defining an object literal you can write:
which sets myProperty to be a reference to myObject2. However, if you write
then myProperty will be set to whatever myObject2.valueOf returns. And finally
sets myProperty to whatever the function body of myObject2 returns. Of course this last one assumes that myObject2 is a Function object. The ability to use an object expression anywhere an object can be used might seem obvious or a small thing - but in practice it turns out to be a very powerful idea that makes a lot of interesting things possible. Often the use is so commonplace that you might not even have noticed that this is exactly what is going on. |
JavaScript Jems - The Revealing Constructor Pattern JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way and sometime it can do unexpectedly clever thing [ ... ] |
JavaScript Canvas - Fetch API Working with lower-level data is very much part of graphics. This extract from Ian Elliot's book on JavaScript Graphics looks at how to use typed arrays to access graphic data. |
| Other Articles |
Comments
or email your comment to: comments@i-programmer.info
<ASIN:0596805527>
<ASIN:193398869X>
<ASIN:0137054890>
<ASIN:1449381871>
<ASIN:1430230541>

