简体   繁体   English

为什么这个称为方法的构造函数返回一个对象?

[英]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(零)将被忽略。

Source 资源

Source 2 来源2

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么对象的构造函数返回Object()而不是其构造函数? - Why does a constructor of an object return Object() instead of its constructor? 为什么构造函数(带有“ return this”)返回窗口对象? - Why does constructor function (with “return this”) return window object? 为什么 map 方法不返回 object 的数组? - Why map method does not return array of object? 为什么对象方法不返回值? - Why does a object method not return a value? 为什么组合构造函数/原型模式返回 typeof 为 object? - Why does combination constructor/prototype pattern return typeof being object? 为什么用构造函数创建对象会在javascript中执行对象的方法? - Why does creating objects with constructor execute object's method in javascript? 为什么我的HTML构造函数对象返回[object Object]而不是[HTMLElementElement]? - Why does my HTML constructor object return [object Object] instead of [HTMLElementElement]? Sencha ExtJs为什么从`constructor`方法返回`this`? - Sencha ExtJs Why Return `this` from `constructor` method? 为什么构造函数只能返回 object? - Why can a constructor only return an object? 为什么构造函数返回与自己名称相同的对象 - Why constructor return object with the same name as itself
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM