在点击事件监听器中使用时,这不是一个功能

时间:2019-04-18 11:24:41

标签: javascript

我正在处理一个javscript文件,并且具有如下代码

dismiss()

除非单击元素,否则代码运行良好,当我单击它时显示class test(){ constructor(){ } showBox(){ var countBlock = document.createElement("div"); document.body.appendChild(countBlock); countBlock.addEventListener('click', function(){ this.showList() }); } showList(){ console.log('Element clicked') } }

不确定如何解决

3 个答案:

答案 0 :(得分:7)

使用arrow function

countBlock.addEventListener('click', () => this.showList());

箭头函数用词法绑定它们的上下文,因此this引用原始上下文,原始上下文是包含箭头函数的代码的上下文。

或使用常规函数,但将封闭的this绑定到您的函数:

countBlock.addEventListener('click', function () { this.showList() }.bind(this));
// or shorter, no need to wrap it in a function:
countBlock.addEventListener('click', this.showList.bind(this));

您可以详细了解this here

以下是基于您的代码的示例:

class Test {
  showBox() {
    const countBlock = document.createElement('p');
    document.body.appendChild(countBlock); 
    countBlock.addEventListener('click', () => this.showList());
  }
  showList() {
    console.log('Element clicked')
  }
}

new Test().showBox();
p {
  width: 20px;
  height: 20px;
  background: black;
  cursor: pointer;
}

答案 1 :(得分:1)

class test(){似乎是错误的,其次使用箭头功能绑定this

class Test {
  constructor() {}
  showBox() {
    console.log('Show Box Executed')
    var countBlock = document.createElement("div");
    let txt = document.createTextNode('Div');
    countBlock.appendChild(txt);
    document.body.appendChild(countBlock);
    countBlock.addEventListener('click', () => {
      this.showList()
    });
  }
  showList() {
    console.log('Element clicked')
  }
}
let _t = new Test();
_t.showBox();

答案 2 :(得分:0)

this.showList 在测试类范围之外,因为您将其包装在匿名函数中。 这样做:

class test{
    constructor(){
    }
    showBox(){
        var countBlock = document.createElement("div");
        document.body.appendChild(countBlock); 
        countBlock.addEventListener('click', this.showList);
    }
    showList(){
        console.log('Element clicked')
    }
}