【问题标题】:Why does XMLHttpRequest() not see external variables? [duplicate]为什么 XMLHttpRequest() 看不到外部变量? [复制]
【发布时间】:2018-07-27 20:18:16
【问题描述】:

这个变量在data内部定义:

data () {
  return {
    isSent: false,
    (...)

尝试在此处调用方法时:

methods: {
  sendEmail () {
    let isSent = this.isSent

    const xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
        this.isSent = true
(...)

linter 说定义了一个未使用的变量。当我删除 let isSent... 初始化时,linter 会说未定义的变量。

我看到了与 JS 闭包相关的问答,但那里的信息虽然有用且广泛,但非常笼统,并不能解决像这样的更具体的问题。

我应该如何从xhr 函数内部获取变量?

【问题讨论】:

  • 好像是在同一个作用域,那你为什么用 this.isSent 来引用它而不是 isSent 呢?
  • 您省略this 的建议是正确的。但范围不同。 sendMail 的作用域不同于 onreadystatechange 的匿名函数。
  • @mbuechmann 有不同的作用域,但内部的仍然指向外部的,这意味着外部作用域的变量是可见的。
  • 更新了我的答案以更清楚地了解它的工作原理,并更改了 closure 示例 以显示它与您的上次编辑无关

标签: javascript vue.js


【解决方案1】:

this 不是你想象的那样。将函数更改为箭头函数,它应该将this 的上下文保留为您所期望的。

xhr.onreadystatechange = () => {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
        this.isSent = true
...

有关箭头函数的更多信息,请参阅documention on MDN

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 2016-05-26
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2011-04-24
    • 1970-01-01
    相关资源
    最近更新 更多