Wednesday, May 21, 2014

javascript return or no return, new or no new, object or function

When the code new foo(...) is executed, the following happens

  1. A new object is created, inheriting from foo.prototype. 
  2. The function foo is executed as constructor.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead.

This is the example of javascript module. It does have return. Shall "new" be used, like var foo = new CoolModule()? Yes, it is allowed. It is equivalent with var foo = CoolModule(), as they both return
I prefer the way not using new, it is straight forward to see that a function CoolModule executed and return an object.

Note: if a non-object value e.g. primitive value is returned, if new is used, the return will be ignored. It still returns the object itself.
The t1 is not '123', it is object {x:'123'}
Another example here
The Apple function does not have return statement. Using "new", an instance of Apple is created and returned. If "new" is not used, no instance of Apple is created and nothing is returned, apple1 will be undefined. Here "new" has to be used.

So, bascially "new" => object, "no new" => function
Object and function are two types in javascript.
Object can be created in 3 ways. {}, new Object(), new function().
The third way used to make me thought object is also a function, but it is not true. Then when we need object and we need function? Function is stateless, object is stateful.

No comments:

Post a Comment