On 12/16/10, Peter van der Zee <[email protected]> wrote:
>>
>> The difference for me is that very first line tells me that I am
>>> creating a new Object.
>>>
>>> var counter = new function() { // must be an object !
>>> //...
>>> }
>>>
>>> Where in contrast:
>>>
>>> var counter = function() { // `counter` is a function?
>>> // ...
>>>
>>> return { };
>>> }(); // No, the function is called immediately, returning {}.
>>>
>>> With newExpression singleton, is that it is clear an object is created
>>> on line 1.
>>>
>>> This must be true because the outer function is called (newed,
>>> actually) immediately, it means that `counter` must be the *result* of
>>> `new` on that function, not the function itself.
>>>
>>>
> Might be interesting to know why this works.
>
That is explained clearly in [[Construct]].
For convenience:
<http://ecma262-5.com/ELS5_Section_13.htm#Section_13.2.2>
> A function is always (ok, virtually always) also a constructor.
Unless otherwise specified, none of the built-in functions (e.g.
`parseInt`, `Function.prototype`, et al) implement [[Construct]].
That means
> you can use `new` on it. From the outside there's no real difference. You
> declare them the same way and they run the same code when you do. There's
> one big difference between the two...
>
> var f = function(){};
>
> If you would do f(); the `this` value would be set to global scope,
Technically speaking, the `this` value would be the global object,
which, coincidentally happens to be the global [[Scope]]. I mention it
becqause beginners often miscall "context" "scope".
or
> possibly something else if you called it differently (x.f(), f.call(y),
> f.apply(y)).
> When you do `new f()`, or even `new f` (the parens are optional if you don't
> pass on arguments!), the `this` value will always be that of a new instance
> of f. So the new keyword before a function call actually calls the
> constructor (but runs the same code).
>
> Other than that, the execution of the function or constructor is the same.
> At the end is where it differs again. A function will always return
> `undefined` unless you return something explicitly. If you do, a function
> will return whatever you want it to return.
> A constructor will return the newly created object (`this`, instance of the
> constructor) unless you use a return statement.
A constructor is required to return an object. If the function call
does not retunr an object then the value returned from [[Construct]]
is the new object that was created in by that algorithm.
[...[]
--
Garrett
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]