【问题标题】:How to access variable name assigned to object from within class constructor in Javascript?如何从 Javascript 的类构造函数中访问分配给对象的变量名?
【发布时间】:2019-08-07 02:02:23
【问题描述】:

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

【问题讨论】:

  • 也许对你有帮助:*.com/questions/29310530/…
  • 你需要使用new关键字来实例化一个类:var S1 = new BigBox()
  • 谢谢。修复了这个问题,但仍然无法正常工作。
  • 嗨。 this."_title" 不是有效的 javascript,或者至少我无法让它在我的控制台中运行。
  • 我认为这是不可能的,也是一种非常糟糕的做法,变量命名不应影响代码的执行。您应该只将一个字符串传递给构造函数并使用它来命名 div。

标签: javascript class constructor this setattribute


【解决方案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");

【讨论】: