我想编写构造函数,以便每次调用对象时,都会使用分配给新类实例的变量名称以及唯一的字符串来创建 CSS 属性。就像这样:
class BigBox{
constructor(){
var div_box = document.createElement("div");
div_box.setAttribute("id", this."_title");
document.body.appendChild(div_box);
}
}
var S1 = new BigBox();
因此,在上面的示例中,目标是将 id 设置为 S1_title,但它不起作用。我做错了什么?
最佳答案
这是一个坏主意,最好将标题传递给构造函数。
class BigBox{
constructor(title){
var div_box = document.createElement("div");
div_box.setAttribute("id", this."_title");
document.body.appendChild(div_box);
}
}
var S1 = new BigBox("S1");
关于javascript - 如何从 Javascript 类构造函数中访问分配给对象的变量名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55191948/