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

问题描述 投票:0回答:1

我想编写构造函数,以便每次调用对象时,都会使用分配给新类实例的变量名称以及唯一字符串创建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,但它不起作用。我究竟做错了什么?

javascript class constructor this setattribute
1个回答
1
投票

这是一个坏主意,最好将标题传递给构造函数。

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");
© www.soinside.com 2019 - 2024. All rights reserved.