2015-09-04 100 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

相关问题