【问题标题】:When does a constructor function return `this` and when does it return what it has been told to return? [duplicate]构造函数什么时候返回`this`,什么时候返回它被告知要返回的内容? [复制]
【发布时间】:2019-11-08 13:39:02
【问题描述】:

看看这个例子。这里定义了两个奇怪的构造函数。我说很奇怪,因为两者都有返回语句并且不返回(隐式)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}

【问题讨论】:

标签: javascript


【解决方案1】:

查看 new 运算符的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

如果函数没有返回自己的对象,则返回this

在 C3 的情况下,您没有返回对象(字符串是原语),所以会返回 'this'。

【讨论】:

    【解决方案2】:

    构造函数总是返回对象。

    不能违反上述规则,如果您尝试这样做(从构造函数返回原语),则会返回默认对象 (this)。

    this SO postherejavascript.info 上查看更多信息。

    这条规则在代理中也是一个不变量,因此当你尝试这样做时它们甚至会抛出错误:

    const p=new Proxy(function(){},{
      construct(){
        return 'ggg'
      }
    })
    
    new p() //TypeError: Construct trap on proxy must return an object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      • 2014-10-25
      • 1970-01-01
      • 2019-07-08
      • 2021-10-11
      相关资源
      最近更新 更多