我已经阅读了大量有关 ES6 的文档以及随之而来的变化。我正在尝试使用一些新的库(例如 fetch)来接受新的 oop 语法。这是我的代码:
apiCall(url, thisAlias=this){
fetch(url).then(function(response){
return response.json();
})
.then(function(respObj){
thisAlias.domUpdater(respObj);
});
}
这是一个具有继承类的基类,并且最终将具有许多继承类。这个想法是使用 fetch 进行通用 api 调用,并且我可以更改每个继承类的 domUpdater 方法。我花了很多时间让这段代码正常工作,给 this 关键字起别名,以便它可以在 fetch 调用中使用。有没有更优雅的方法来做到这一点?我似乎无法直接将其作为参数传递。
最佳答案
使用arrow functions具有词法 this
的内容将对您对这段特定代码提供最大帮助
apiCall (url) {
fetch(url).then(
response => response.json()
).then(
respObj => this.domUpdater(respObj)
).catch(
err => console.error(err.message, err)
)
}
否则,如果您可以使用较新的 async
/await
,则不必担心 this
指向错误的内容全部 - 即使没有箭头功能。
<b>async</b> apiCall (url) {
try {
let response = <b>await</b> fetch(url);
this.domUpdater(response.json());
}
catch (err) {
console.error(err.message, err);
}
}
关于javascript - 如何使用 "this"和 fetch ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40254148/