[英]Why does this constructor called method return an object?
I figued putting the class method inside the constructor would return the <h1>
but this is not the case. 我想把类方法放在构造函数中会返回<h1>
但事实并非如此。 Instead it returns an object/the class. 而是返回一个对象/类。
Why does it behave this way instead of returning the <h1>
element? 为什么它表现为这种方式而不是返回<h1>
元素?
It seems only doing it this way will it work: new Foo(data).createText();
似乎只有这样才能起作用: 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. 如果构造函数不返回任何值,null或任何原子/非对象值,则将忽略该值,并将新创建的对象引用返回给调用方。 For example, a return value of 0 (zero) from a constructor function will be ignored. 例如,构造函数的返回值0(零)将被忽略。
从对象到字符串的默认转换为[对象对象]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.