代码之家  ›  专栏  ›  技术社区  ›  ProEvilz

为什么这个名为method的构造函数返回一个对象?

  •  0
  • ProEvilz  · 技术社区  · 8 年前

    我发现将类方法放在构造函数中会返回 <h1> 但事实并非如此。 相反,它返回一个对象/类。

    为什么它这样做而不是返回 <h1> 元素?

    似乎只有这样才能奏效: new Foo(data).createText(); 是吗?

    const data = "This is a title";
    
    
    class Foo {
      constructor(data) {
        this._title = data;
        this.createText();
      }
    
      createText() {
        return `<h1> ${this._title} </h1>`;
      }
    }
    
    const targ = document.getElementById('targ');
    
    //Why doesn't this work considering it's called in the constructor?
    targ.innerHTML = new Foo(data);
    
    targ.innerHTML += new Foo(data).createText();
    <div id="targ"></div>
    2 回复  |  直到 8 年前
        1
  •  1
  •   Get Off My Lawn    8 年前

    如果构造函数不返回任何值、空值或任何原子/非对象值,则忽略该值,并将新创建的对象引用返回给调用方。例如,构造函数的返回值0(零)将被忽略。

    Source

    Source 2

        2
  •  0
  •   Roy G    8 年前

    从对象到字符串的默认转换是[object object]