【问题标题】:Why does setting the condition of an variable to be undefined give an error?为什么将变量的条件设置为未定义会出错?
【发布时间】:2021-08-27 05:39:10
【问题描述】:

我希望该功能在第一次点击时只运行一次,不再运行。但是我收到一个错误,someVar 没有定义,这就是我在条件中包含的内容。为什么它给出错误?如何解决?

button.onclick = function () {
  if (someVar == undefined) {
    console.log("Hi");
    someVar = 1; 
  }
}

【问题讨论】:

  • if上方添加这个let someVar;

标签: javascript function if-statement variables


【解决方案1】:

this 方法(this 引用onClickfunction):

const button = document.querySelector('button')

button.onclick = function () {
  if (this.someVar == undefined) {
    console.log("Hi");
    this.someVar = 1; 
  }
}
<button>button</button>

全局变量方法:

const button = document.querySelector('button')

let someVar = undefined;

button.onclick = function () {
  if (someVar == undefined) {
    console.log("Hi")
    someVar = 1;
  }
}
<button>button</button>

【讨论】:

    【解决方案2】:

    您是否将 someVar 定义为全局变量? 像这样使用它=>

    var someVar = undefined;
    button.onclick = function () {
      if (this.someVar == undefined) {
        console.log("Hi");
        this.someVar = 1; 
      }
    }
    

    【讨论】:

    • 变量不是已经未定义了吗?
    • 如果你使用this,你甚至不需要定义someVar。在这种情况下,this.someVarsomeVar 甚至是两个不同的变量,someVar 将始终是 undefined,并且在这种情况下不使用...
    • @ulou 不,如果你全局声明一个变量,它将成为全局对象window 的属性,甚至在处理程序中this 也是窗口,因此它将是同一个变量。
    • 不,它不会,除非你将bind thisonClick function
    • @ulou 似乎这是addEventListener 和直接分配给onclick 之间的区别。所以你是对的
    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    相关资源
    最近更新 更多