看这个例子。这里定义了两个奇怪的构造函数。我说奇怪是因为两者都有返回语句并且不返回(隐式)this
就像通常的构造函数一样。
但奇怪的是......当用 new
调用时运算符...
1) C3 返回新构造的 this
对象,即使它被告知返回“ggg”。
2) C2 返回它被告知要返回的内容(不是 this
对象)。
为什么会有这种行为差异? C2和C3在概念上有什么区别?
构造函数何时返回 this
它什么时候返回被告知要返回的内容?
function C2() {
this.a = 1;
return {b: 2};
}
var c2 = new C2();
console.log(c2.a); //undefined
console.log(c2.b); //2
console.log(c2); //{b:2}
function C3() {
this.a = 1;
return "ggg";
}
var c3 = new C3();
console.log(c3.a); //1
console.log(c3); //C3 {a: 1}
最佳答案
查看新运算符的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
Returns
this
if the function doesn't return its own object.
对于 C3,您不会返回对象(字符串是基元),因此返回“this”。
关于javascript - 构造函数何时返回 `this` 以及何时返回被告知要返回的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58757307/