问题
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.
回答1:
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.
回答2:
When the code new Foo(...) is executed, the following things happen:
1- A new object is created, inheriting from Foo.prototype
.
2- The constructor function Foo is called with the specified arguments and this bound to the newly created object. new Foo is equivalent to new Foo()
, i.e. if no argument list is specified, Foo is called without arguments.
3- The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
function Car() {}
car1 = new Car();
console.log(car1.color); // undefined
Car.prototype.color = null;
console.log(car1.color); // null
car1.color = "black";
console.log(car1.color); // black
You can find a complete description Here
来源:https://stackoverflow.com/questions/35311205/javascript-constructor-return-values