javascript - New function returning new function -
i'm getting bit confused new keyword in javascript. take following example
function (value) { this.a = value; } function b (value) { return new (value); } console.log ( b (0)); // { a: 0 } console.log (new b (0)); // { a: 0 }
i want able create new instance of "a" without having use "new". have "b()", however, when call "new b()" appears same thing "b()", though "new" ignored. in both cases, instanceof equals "a". going on?
from the mdn on new
:
the object returned constructor function becomes result of whole new expression. if constructor function doesn't explicitly return object, object created in step 1 used instead. (normally constructors don't return value, can choose if want override normal object creation process.)
this extract shows that
- what
new b
isn't "normal" (there's no reason that) - the value explicitely returned
b
returnednew b
you won't confused if stick normal use of new
: passing normal constructor, function doesn't return initialize context (this
).
Comments
Post a Comment