3
在瀏覽器中,我嘗試使用ES6承諾和ES6獲取,使用Reflux.js操作,但是我在綁定匿名箭頭函數中的'this'的上下文時遇到了問題。我究竟做錯了什麼?Es6訪存/承諾上下文
*更新* 我使用Reflux.js ListenAndPromise,我大概應該在我的一部開拓創新的問題添加此
*更新*
得到了環境中工作時,我刪除外部箭頭功能 這工作:
CrewActions.fetchCrew.listenAndPromise(function() {
fetch('crew.json')
.then(function() {
console.log(this); // This is bound as expected
}.bind(this))
});
但這不起作用
CrewActions.fetchCrew.listenAndPromise(function() {
fetch('crew.json')
.then(() => {
console.log(this); // undefined
})
});
所以我想我是錯上箭頭的功能是如何工作的?我認爲他們限制了這個背景?
下面的例子都不起作用。
例子。
CrewActions.fetchCrew.listenAndPromise(() => {
console.log(this)
// functor() {
// var triggerType = functor.sync ? "trigger" : "triggerAsync";
// return functor[triggerType].apply(functor, arguments);
// }
fetch('crew.json')
.then(_.bind(() => {
console.log(this) // undefined
}, this))
fetch('crew.json')
.then(() => console.log(this)); // undefined
fetch('crew.json')
.then(function() {
console.log(this) // undefined
});
fetch('crew.json')
.then(function() {
console.log(this) // undefined
}.bind(this));
});
在第一種情況下,您無法綁定箭頭函數。對於其餘的問題,首先定義的是什麼?最後一個例子應該可以,試試 。然後(function(){console.log(this)}。bind({jellybeans:true}))並且它應該記錄jellybeans對象。 – Dtipson
節點還是瀏覽器?請提供[mcve] –
這些調用是在全局上下文中還是在對象實例中調用的? – Icepickle