if I have function like this:
function Apple(){
this.color = "green";
return this;
}
When creating object like this:
var my_obj = new Apple();
is that line return this;
necessary and/or is it valid by language reference?
if I have function like this:
function Apple(){
this.color = "green";
return this;
}
When creating object like this:
var my_obj = new Apple();
is that line return this;
necessary and/or is it valid by language reference?
It is not necessary.
The function will implicitly return a new
Object
when instantiated with thenew
operator.this
will refer to that new object in that context.Invalid returns (such as primitives or non new objects) will still return the standard
this
.You can override it by returning a new different object.
jsFiddle.
No, returning
this
is not necessary, but it is valid. If the returned value is an object,new
will return that object instead of the newly created object.See points 11.2.2 and 13.2.2 of ECMAScript 5:
The new operator calls the internal [[Construct]] method on the constructor (usually a function):
The [[Construct]] internal method of functions is described in point 13.2.2:
It is not necessary, a constructor automatically returns the newly created object.
About explicitly returning a value from constructor this page has good information: JavaScript: Constructor Return Value
Quote:
and