Return Statement in JS Constructors

邮差的信 提交于 2020-01-29 03:51:09

问题


What is the effect of a return statement in the body of JavaScript function when it's used as a constructor for a new object(with 'new' keyword)?


回答1:


Usually return simply exits the constructor. However, if the returned value is an Object, it is used as the new expression's value.

Consider:

function f() {
   this.x = 1;
   return;
}
alert((new f()).x);

displays 1, but

function f() {
   this.x = 1;
   return { x: 2};
}
alert((new f()).x);

displays 2.




回答2:


The reason to use the new operator is to ensure that this inside the constructor refers to a new context, which supports:

this.functionName = function(){...};

, and to allow the use of the instanceof operator:

function foo() {...}
var bar = new foo();
alert(bar instanceof foo);

Using return {...} inside such a constructor negates both of these effects as this will not be needed with such a pattern, and as instanceof will return false.



来源:https://stackoverflow.com/questions/2938940/return-statement-in-js-constructors

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