简体   繁体   English

Javascript 旧语法到箭头函数的转换

[英]Javascript old syntax to arrow function conversion

So I want to use this example without jquery or other libraries.所以我想在没有 jquery 或其他库的情况下使用这个例子。

I have this code我有这个代码

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

As you can see it uses the old style function()如您所见,它使用旧样式的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.同样,我不想在这个练习中使用库。

The problem with arrow functions is that they keep the this object of the outer scope.箭头函数的问题在于它们保留了外部作用域的this对象。

Your first example would have the XMLHttpRequest bound to the this reference the second the window您的第一个示例会将XMLHttpRequest绑定到第二个windowthis引用

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:要使用箭头符号进行此操作,您需要使用外部名称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 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Be aware that you can not override the this reference of arrow functions by any mean (bind, call, apply)请注意,您不能以任何方式覆盖箭头函数的this引用(绑定、调用、应用)

Bellian's code above looks nice but the .bind(undefined, request); Bellian 上面的代码看起来不错,但是.bind(undefined, request); gives the simplicity away.放弃简单。

There's an alternate way of doing this in such a way that it would sync to your questions expected answer:有一种替代方法可以同步到您的问题预期答案:

I highly recommend you should do this instead.我强烈建议你应该这样做。 The arrow function removed the direct this to gain better access to the results.箭头函数删除了直接this以更好地访问结果。 Check for yourself console.log(x) only without the .target仅在没有.target情况下检查自己的console.log(x)

You can also:您还可以:

 let xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = x => { let result = x.target; if(result.readyState == 4 && result.status == 200){ console.log(result.responseText); } };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM