我想编写构造函数,以便每次调用对象时,都会使用分配给新类实例的变量名称以及唯一字符串创建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");