这个问题已经在这里有了答案: > How to access the correct `this` inside a callback? 10个
通过查看这段代码,我对在打字稿中使用此代码感到有些困惑
class GoogleMapsClass { public map; constructor(selector) { var _this = this; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { _this.map = this.responseText; } }; xhttp.open("GET", "/test.PHP", false); xhttp.send(); } }
@H_502_9@您可以看到我正在使用上下文切换技巧var _this = this;
我不知道这是否是处理Typescript中的类字段的正确方法,我也担心通过使用此技巧,我只是复制了内存,因此对性能和整体代码质量均不利(我知道JS并非为进行一些繁重的操作而创建的对象,但是在优化代码时,复制对象是最简单的错误).
处理上下文切换的最正确方法是什么?
解决方法:
您的代码中没有重复的对象. _this只是对此的引用.实际上,您可以使用箭头函数或绑定函数来避免_this.
bind:
class GoogleMapsClass { public map; constructor(selector) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4) { this.map = xhttp.responseText; } }.bind(this); xhttp.open("GET", "/test.PHP", false); xhttp.send(); } }
@H_502_9@class GoogleMapsClass { public map; constructor(selector) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = () => { if (xhttp.readyState == 4) { this.map = xhttp.responseText; } } xhttp.open("GET", "/test.PHP", false); xhttp.send(); } }
@H_502_9@版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。