在onclick函数中获取Class的变量

时间:2019-04-19 02:08:49

标签: javascript

我遇到一个问题,我无法在同一类的另一个变量的onclick函数内访问该类的国家变量。我做了一个小演示,在其中分配消息并返回显示消息的button,但由于找不到变量,它继续打印undefined。请帮助

class class1 {
  message = "";
  clicker = document.createElement("button");
  
  constructor(sentence) {
    this.message = sentence;
    this.clicker.id = "clicker";
    this.clicker.innerHTML = "CLICK ME";
    this.clicker.addEventListener("click", (function () {
        console.log(this.message);
    }).bind(this))
    return this.clicker;
  }
}

document.getElementById("content").appendChild(new class1("hello"));
<html>
<head>
  <title></title>
</head>
<body>
  <div id='content'></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

该函数与触发事件的HTML元素绑定,您可以使用箭头函数或绑定所需的特定词法上下文。

使用箭头功能。

class class1 {
  message = "";
  clicker = document.createElement("button");
  
  constructor(sentence) {
    this.message = sentence;
    this.clicker.id = "clicker";
    this.clicker.innerHTML = "CLICK ME";
    this.clicker.onclick = () => {
      console.log(this.message);
    }
    return this.clicker;
  }
}

document.getElementById("content").appendChild(new class1("hello"));
<html>
<head>
  <title></title>
</head>
<body>
  <div id='content'></div>
</body>
</html>

绑定

class class1 {
  message = "";
  clicker = document.createElement("button");
  
  constructor(sentence) {
    this.message = sentence;
    this.clicker.id = "clicker";
    this.clicker.innerHTML = "CLICK ME";
    this.clicker.onclick = (function() {
      console.log(this.message);
    }).bind(this)
    return this.clicker;
  }
}

document.getElementById("content").appendChild(new class1("hello"));
<html>
<head>
  <title></title>
</head>
<body>
  <div id='content'></div>
</body>
</html>