Question
There are two popular closure styles in javascript. The first I call anonymous constructor:
new function() {
var code...
}
and the inline executed function:
(function() {
var code...
})();
are there differences in behaviour between those two? Is one "better" over the other?
Answer
Both cases will execute the function, the only real difference is what the return value of the expression may be, and what the value of "this" will be inside the function.
Basically behaviour of
new expression
Is effectively equivalent to
var tempObject = {};
var result = expression.call(tempObject);
if (result is not an object)
result = tempObject;
Although of course tempObject and result are transient values you can never see (they're implementation details in the interpreter), and there is no JS mechanism to do the "is not an object" check.
Broadly speaking the "new function() { .. }" method will be slower due to the need to create the this object for the constructor.
That said this should be not be a real difference as object allocation is not slow, and you shouldn't be using such code in hot code (due to the cost of creating the function object and associated closure).
Edit: one thing i realised that i missed from this is that the tempObject will get expressions prototype, eg. (before the expression.call) tempObject.__proto__ = expression.prototype
0 comments:
Post a Comment