Javascript constructor return values [duplicate]

戏子无情 提交于 2019-12-20 01:45:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!