2016-02-25 70 views
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)); 
 
});

+2

在第一種情況下,您無法綁定箭頭函數。對於其餘的問題,首先定義的是什麼?最後一個例子應該可以,試試 。然後(function(){console.log(this)}。bind({jellybeans:true}))並且它應該記錄jellybeans對象。 – Dtipson

+1

節點還是瀏覽器?請提供[mcve] –

+2

這些調用是在全局上下文中還是在對象實例中調用的? – Icepickle

回答

1

當我嘗試的是,Arrow功能版本的簡化版本:

function listenAndPromise() { 
console.log('outer fn',this); 
    return fetch('crew.json') 
    .then(() => { 
    console.log('arrowfn',this); // undefined 
    }) 
} 
listenAndPromise.bind({test:4})(); 

它記錄,外FN對象{試驗:4}然後arrowfn對象{測試:4}

這就是我所期望的。外部函數被賦予一個上下文,而箭頭函數不會添加新的「this」上下文/含義。您的結果可能與您的環境(或CrewActions.fetchCrew.listenAndPromise與「this」綁定的內容)有關,而不是內部函數本身。