JavaScript Jems - Objects with Values
Written by Ian Elliot   
Thursday, 23 May 2019
Article Index
JavaScript Jems - Objects with Values
toString
Using factory objects and constructors
Functions v Objects

 

Functions Versus Objects

You have a choice of associating a value with an object as in:

myObject+1;

or you can define a function that does the same thing:

myFunction()+1;

The difference is that the function has a natural way to accept arguments.

For example, you can write:

myFunction(10)+1;

but without defining it to be a function you can't write:

myObject(10)+1;

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.

Consider the JavaScript date object:

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.

Now that you have seen how to create default values you can think up your own uses for them. In some situations it can simplify the use of your objects by allowing them to be used in expressions.

 

Now available as a book from your local Amazon.

JavaScript Jems:
The Amazing Parts

kindlecover

JavaScript Jems - Functional And Not Quite Functional

Original drafts of chapters.

Contents

  1. JavaScript Patterns 
    Why JavaScript is a Jem
  2. Objects with Values in JavaScript*
  3. Private Functions In JavaScript
  4. Chaining - Fluent Interfaces In JavaScript*
  5. Active Logic, Truthy and Falsey*
  6. The Confusing Comma In JavaScript*
  7. Self Modifying Code*
  8. Lambda expressions
  9. Meta Programming Using Proxy
  10. Master JavaScript Regular Expressions
  11. The Function Approach To Programming

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:1871962501>

<ASIN:1871962528>

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 



Last Updated ( Tuesday, 06 August 2019 )