javascript - Behavior of 'return' and 'new' in constructors -
i wonder what's difference between these 2 calls:
var = array(1,2,3); var b = new array(1,2,3);
i tried mimic behavior way:
function test() { return {x:42}; } var = test(); var b = new test(); console.log(a,b); // same
how possible b
same a
? if new
used, return value should ignored:
function test() { return 1; } var = test(); var b = new test(); console.log(a,b); // 1 test{}
when call function using new
, new object created , passed function this
. if function doesn't return (or returns primitive), new object passed in result of new
expression. but, if function returns object, new object created thrown away , object returned function result of new
expression instead. covered in turgid prose in section 11.2.2 of spec. it's useful immutable objects constructor maintains kind of cache , reuses instances if arguments identical (or of course, singletons).
so in example, since test
function returns object, calling via new
creates , throws away object created new
operator, , result object you're returning test
instead.
i shouldn't object new
"thrown away" if return different object. constructor might object new
keeps being thrown away. instance, write constructor this:
function weirdconstructor() { return { thenewobject: }; }
...which takes object created new
, makes property of object returns. call special scenario put mildly. :-)
the fact array(1, 2, 3)
, new array(1, 2, 3)
both return new array special feature of array
constructor, covered section 15.4.1. spec lays out each of standard constructors if don't call them via new
. behavior varies. many of them type coercion, couple array
act used new
though didn't, , date
weird thing (gives string version of current date, string(new date())
).
specifically regarding array
: wouldn't use either array(1, 2, 3)
or new array(1, 2, 3)
. i'd use [1, 2, 3]
. it's not ambiguous (does new array(3)
create blank array length = 3
or array 1 entry, 3
, in it? new array("3")
?), , it's possible (though unlikely) shadow symbol array
, can't shadow literal form. don't think point of question. :-)
Comments
Post a Comment