JavaScript 使用布尔值来控制回调



我有一个布尔变量,我最初声明为真。

我有一个.on('click')事件,它检查布尔值是否为真,如果是,如果调用function1function1将布尔值设置为 false。

如果 bool 为假function2则调用并将 bool 设置为 true。

但是,布尔值没有正常工作,我不知道为什么。

我的代码如下:

cells.on('click', function(d, i) {
      if (d.vis === 'text') {
        console.log('test');
        if (this.boolGame == true) {
          myThis.updateList(d);
          console.log('setting false');
        } else if (this.boolGame == false) {
          myThis.collapseList();
          console.log('true');
        }

这是其中一个函数的示例

 collapseList() {
    let gameList = this.tableElements.filter(d => d.value.type == 'games');
    console.log(gameList);
    // this.tableElements.splice();
    console.log('false');
    this.boolGame = false;
}

尝试使用 console.log(this.boolGame) .它不起作用,因为它很undefined.使用 function 语法创建的函数具有自己的上下文。例如,它创建了自己的this变量,并且不包含您在上面的范围内设置的任何属性。您有两种选择:使用 bind 或箭头函数。

  1. bind .将其转换为命名函数并对其使用 bind。这将创建具有您正在寻找的内部上下文的this.cellsHandler副本。

    this.cellsHandler = function(d, i) {
      if (d.vis === 'text') {
        console.log('test');
        if (this.boolGame == true) {
          myThis.updateList(d);
          console.log('setting false');
        } else if (this.boolGame == false) {
          myThis.collapseList();
          console.log('true');
        }
      }
    }
    cells.on('click', this.cellsHandler.bind(this))
    
  2. 将函数转换为箭头函数。箭头函数没有上下文,因此它从其上方的作用域中获取this,该作用域包含boolGame。我推荐这种方法。

    cells.on('click', (d, i) => {
      if (d.vis === 'text') {
        console.log('test');
        if (this.boolGame == true) {
          myThis.updateList(d);
          console.log('setting false');
        } else if (this.boolGame == false) {
          myThis.collapseList();
          console.log('true');
        }
      }
    }
    

最新更新