Javascript旧语法到箭头函数的转换 [英] Javascript old syntax to arrow function conversion

查看:354
本文介绍了Javascript旧语法到箭头函数的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I want to use this example without jquery or other libraries.

我有此代码

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

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

As you can see it uses the old style function()

如何将其更改为箭头功能样式?

How do I change this to an arrow function style one?

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

这不起作用. 我要关闭还是我完全看错了?同样,我不想在本练习中使用库.

This doesn't work. Am I close or am I looking at this completely wrong? Again I don't want to use libraries for this exercise.

推荐答案

箭头功能的问题在于它们保留了外部作用域的this对象.

The problem with arrow functions is that they keep the this object of the outer scope.

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

Your first example would have the XMLHttpRequest bound to the this reference the second the window

要使用箭头符号实现此目的,您需要使用外部名称xmlHttp引用XMLHttpRequest或将其绑定到回调函数:

To make this work with arrow notation, you need to reference the XMLHttpRequest with the outer name xmlHttp or bind it to the callback function:

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

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

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

Be aware that you can not override the this reference of arrow functions by any mean (bind, call, apply)

这篇关于Javascript旧语法到箭头函数的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆