以下代码演示了相同的情况。
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
我的假设正确吗?
答案 0 :(得分:2)
如果函数未返回其自己的对象,则返回
this
。 new operator
在您的第一个函数中,您将返回一个{}
,因此当您访问
new test(x).x
您实际上正在访问{}.x
的{{1}}
第二个功能
undefined
实际上正在访问功能new test(x).x
中添加的x
属性