JS 构造函数中的返回语句

2022-01-19 00:00:00 return constructor javascript

当 JavaScript 函数体中的 return 语句用作新对象的构造函数时(带有 'new' 关键字)有什么作用?

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)?

推荐答案

通常return简单的退出构造函数.但是,如果返回的值是一个 Object,则它被用作 new 表达式的值.

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

考虑:

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

显示 1,但是

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

显示 2.

相关文章