2015-09-04 64 views
3

ES6還是個新手,所以試圖理解下面這兩個函數之間存在差異的原因。我正在使用React,並且注意到在編寫設置狀態的非ES6函數時出現錯誤。這發生在componentDidMount中。這個ES6箭頭函數和常規函數的區別?

這樣在ES6工作並返回我需要什麼:

(pos) => this.setState({ 
    lat: pos.coords.latitude, 
    lng: pos.coords.longitude, 
    }) 

然而,這種方式會引發錯誤 - 「遺漏的類型錯誤:this.setState是不是一個函數」

function(pos) { 
    this.setState({ 
     lat: pos.coords.latitude, 
     lng: pos.coords.longitude 
    }) 
    } 

這些不完全一樣嗎?任何人都可以解釋爲什麼它會拋出這個錯誤?

下面是代碼從反應類,以提供更多的上下文:

var GeolocationExample = React.createClass({ 
    getInitialState: function() { 
    return { 
     lat: '', 
     lng: '', 
    }; 
    }, 

    componentDidMount: function() { 
    navigator.geolocation.getCurrentPosition(

     // Where I'm placing each of the above mentioned functions, 

     (err) => alert(err.message), 
    ); 
    }, 

    render: function() { 
    return (
     <View> 
     <Text> 
      <Text style={styles.title}>Initial position: </Text> 
      {this.state.lat} 
     </Text> 
     <Text> 
      <Text style={styles.title}>Current position: </Text> 
      {this.state.lng} 
     </Text> 
     </View> 
    ); 
    } 
}); 

任何和所有的幫助表示讚賞。謝謝!

+0

'的console.log (this)' – Andreas

+1

as @Andrey指出:'箭頭函數隱含了這個綁定',所以帶有'(function(pos){...})。bind(this)'的非箭頭應該等同於箭頭1 – birdspider

回答

7

不,他們不一樣。箭頭函數自動綁定到創建它們的上下文中。 這意味着,

(x) => this.stuff = x 

是(大部分)等效於:

(function(x) { 
    return this.stuff = x; 
}.bind(this)) 

箭頭功能也將保留argumentssuper和在其內部創建它的功能的new.target

這意味着

(function a() { 
    const u =() => console.log(arguments); 
    u("whatever"); 
})("a args"); 

將打印出類似這樣["a args"]

有關更多信息,請參見here

+0

謝謝你的明確解釋 - 非常感謝! – hidace

+0

還有更多它,但這是一個很好的介紹。 'arguments','super'和'new.target'在箭頭函數中工作。當沒有'this'被初始化時,也可以創建箭頭函數,就像調用'super()'之前的類構造函數中一樣。 – loganfsmyth

+0

哦,這是正確的。更確切地說,就像'this'一樣,它們從創建它們的函數中保存這些值。我其實並不知道這一點。謝謝。 –

0

Lexical this

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

From : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

這就是爲什麼,當你寫:

this.setState = function() {}; 
function(pos) { 
    this.setState({ 
     lat: pos.coords.latitude, 
     lng: pos.coords.longitude 
    }) 
    } 

this.setStatethis內部功能設置爲{}(空物體)。

當你用=>符號寫相反,這是與功能外,這相當於共享:

this.setState = function() {}; 
var self = this; 
function(pos) { 
    self.setState({ 
     lat: pos.coords.latitude, 
     lng: pos.coords.longitude 
    }) 
    } 

,或者您也可以使用function(pos){ /* Stuff here */ }.bind(this);

+0

謝謝 - 非常有幫助! – hidace

+1

「*這證明是令人討厭的一種面向對象的編程風格*」 - 等什麼?如果沒有'this',面向對象的編程幾乎是不可能的! – Bergi

+3

不,'setState'中的'this'不*設置爲'{}'。你從哪裏得到那個的? – Bergi

相關問題