>
> 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.
A function is always (ok, virtually always) also a constructor. 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, 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. And this is where there's a
subtle difference, if the return statement in a constructor returns a
"primitive value" (a number, string, bool, undefined or null), the statement
is "ignored" and the `this` object is returned anyways. Only when you return
an object, that value is actually returned.
Hrm. I was gonna say a constructor is slightly slower than a regular
function call, but it seems that information is outdated, as demonstrated in
this jsperf:
http://jsperf.com/function-vs-constructor-vs-eval
Note that in js, if you are going to declare a constructor, it's name
"should" start with a capital. That way you know it's intended to be a
constructor, rather than a normal function.
- peter
--
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]