如果函数返回一个对象,则它不能充当JS中的构造函数。我的假设正确吗

时间:2019-06-09 09:20:56

标签: javascript function return new-operator

以下代码演示了相同的情况。

function test(x) {
  this.x = x;
  return {};
}

function test1(x) {
  this.x = x;
}

console.log(new test(1).x); // logs undefined 

console.log(new test1(1).x); // logs 1

我的假设正确吗?

1 个答案:

答案 0 :(得分:2)

  

如果函数未返回其自己的对象,则返回thisnew operator

在您的第一个函数中,您将返回一个{},因此当您访问

new test(x).x

您实际上正在访问{}.x的{​​{1}}

第二个功能

undefined实际上正在访问功能new test(x).x中添加的x属性