Consider the following code:
function Foo() {
return "something";
}
var foo = new Foo();
According to the experts in JavaScript, they say that return "nothing" or just "this" from a constructor. Whats the reason for this?
I am aware that when used "new", the "this" would be set to the prototype object of the constructor but not able to understand this point alone.
That particular code will throw a ReferenceError because something
is not declared.
You should either return this
or have no return statement at all in a constructor function because otherwise you will have constructed a new instance of the class (the value of this
, and the default return value) and then thrown it away.
I am aware that when used "new", the "this" would be set to the prototype object of the constructor
Incorrect. It will be set to an instance of the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With