Question

Below documentation shows the usage of Observable with and without the "new" keyword.

http//dojotoolkit.org/reference-guide/1.9/dojo/store/Observable.html

   // create the initial Observable store
  store = new Observable(new Memory({data: someData})); 

http//dojotoolkit.org/documentation/tutorials/1.6/realtime_stores/

  Note: despite its capital "O" and dedicated module, dojo.store.
  Observable is not a    constructor; it is simply a function which 
  takes a store, wraps it with observe functionality, then returns it.
  Therefore, the new keyword should not be used with dojo.store.Observable. 

http://dojotoolkit.org/documentation/tutorials/1.7/realtime_stores/

  // wrap the store with Observable to make it possible to monitor: 
  marketStore = Observable(marketStore); 

What is the correct usage? If both are correct? when should a particular usage be preferred over the other.

Frank.

Was it helpful?

Solution

It doesn't really matter. What happens behind the screens is very similar. When you call the Observable as a function like:

var store = Observable(new Memory({ data: [] }));

Then it will use return value of the Observable() method (which is the observable store).

When you're using the new keyword, you're creating a new instance of Observable, in JavaScript that means that the Observable() function itself will be seen as the constructor of the new instance.

However, when you're providing a return value from inside the constructor, that object (when being a complex object) is used as the instance in stead. So in this case it returns the observable store, so that will be used as the instance. A good article to read what happens if something is being returned from a constructor function can be found here.

The naming of it (starting with a capital letter) makes you think it's an instance of Observable, but it isn't. The ultimate proof to that is the following:

new Observable(new Memory({ data: [] })) instanceof Observable // Returns false

The following returns false and in case of a real instance it would return true.


Summarized, both ways will return an observable store. There is no difference in it, even performance wise both are very similar.

So it doesn't really matter what you use, the only thing I can tell you is that it behaves like a normal function and not as a constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top