为什么这个构造函数调用方法 return 一个对象?
Why does this constructor called method return an object?
我认为将 class 方法放在构造函数中会 return <h1>
但事实并非如此。
相反,它 return 是 object/the class。
为什么它会这样而不是 returning <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>
If a constructor function returns nothing, null, or any atomic / non-object value then said value is ignored and the newly created object reference is given back to the caller. For example, a return value of 0 (zero) from a constructor function will be ignored.
Source 2
从对象到字符串的默认转换是 [object Object]
我认为将 class 方法放在构造函数中会 return <h1>
但事实并非如此。
相反,它 return 是 object/the class。
为什么它会这样而不是 returning <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>
If a constructor function returns nothing, null, or any atomic / non-object value then said value is ignored and the newly created object reference is given back to the caller. For example, a return value of 0 (zero) from a constructor function will be ignored.
Source 2
从对象到字符串的默认转换是 [object Object]