【问题标题】:Javascript old syntax to arrow function conversionJavascript 旧语法到箭头函数的转换
【发布时间】:2017-07-25 09:45:14
【问题描述】:

所以我想在没有 jquery 或其他库的情况下使用这个示例。

我有这个代码

let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {...}

如您所见,它使用旧样式function()

如何将其更改为箭头函数样式?

let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = () => {...}

这不起作用。 我是接近还是我完全看错了?同样,我不想在这个练习中使用库。

【问题讨论】:

  • 这确实有效。错误在其他地方
  • 它不起作用是什么意思?浏览器不支持?你也可以使用const 而不是let 我怀疑你重新分配xmlHttp
  • sn-p 在 chrome v59 中工作。你用的是什么浏览器。可能是浏览器还不支持箭头功能,可能需要我尝试过的 polyfill:let xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = () => {console.log('s')}
  • 您可能正在尝试在函数中使用this,这与箭头函数的工作方式不同。作业没有任何问题。
  • @DarthJDG 你的 cmets 是票 - 我将 this 更改为 xmlHttp 这是变量名并且它有效。我将阅读箭头函数的this 部分:-)

标签: javascript ajax xmlhttprequest arrow-functions


【解决方案1】:

箭头函数的问题是它们保留了外部作用域的this对象。

您的第一个示例将XMLHttpRequest 绑定到this 引用第二个window

要使用箭头表示法,您需要使用外部名称 xmlHttp 引用 XMLHttpRequest 或将其绑定到回调函数:

let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ((request) => {...}).bind(undefined, request);

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

请注意,您不能以任何方式(绑定、调用、应用)覆盖箭头函数的 this 引用

【讨论】:

  • 感谢您的解释 - 如果允许我会接受答案
【解决方案2】:

上面 Bellian 的代码看起来不错,但 .bind(undefined, request); 让简单性消失了。

还有另一种方法可以做到这一点,它可以与您的问题预期答案同步:

我强烈建议您改为这样做。箭头函数删除了直接的this,以便更好地访问结果。仅在没有.target 的情况下自行检查console.log(x)

您还可以:

let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = x => {
  let result = x.target;

        if(result.readyState == 4 && result.status == 200){         
            console.log(result.responseText);
            
        }
    
};

【讨论】:

    猜你喜欢
    • 2017-03-05
    • 2023-02-22
    • 2017-12-06
    • 2021-04-14
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2017-08-15
    • 2019-03-20
    相关资源
    最近更新 更多