如何从 Javascript 中的 class 构造函数中访问分配给对象的变量名?

How to access variable name assigned to object from within class constructor in Javascript?

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