gpt4 book ai didi

javascript - ES2015 : call method from the construcror

转载 作者:行者123 更新时间:2023-11-28 18:10:06 24 4
gpt4 key购买 nike

当创建 ES2015 类的新实例时,我需要将 DOM 元素添加到某个容器中。看起来不可能从构造函数中调用该方法。

let titleCounter = 0;

class Header{

constructor(){

titleCounter++;
this.id = 'title'+titleCounter;
this.html = `
<div class="${this.id}" style="background-color: blue;">Title</div>
`;

//addDOMtoField(); // don't work
$('#container').append(this.html);
}

addDOMtoField(){
$('#container').append(this.html);
}
}

let instance1 = new Header();
#container{
min-height: 5px;
background-color: green;
padding: 5px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'>

</div>

比在构造函数中添加 $('#container').append(this.html); 更优雅的东西吗?

最佳答案

在 JavaScript 中,类字段和方法名称不能用作构造函数和其他方法中的变量名称绑定(bind);它们只能通过对实例的引用来访问,而实例的引用可以通过 this 获取。

因此,您必须使用 this.addDOMtoField() 而不仅仅是 addDOMtoField()

关于javascript - ES2015 : call method from the construcror,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41818266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com