鍍金池/ 問答/HTML/ js的方法定義問題

js的方法定義問題

看到有js代碼如下
圖片描述

感覺很疑惑的地方就是

renderTag = (film: Film) => {
    return film.tagInfo ? film.tagInfo : film.title;
};

selectFilm(film: Film) {
    this.setState({films: [...this.state.films, film]});
}

這兩個(gè)不都是定義一個(gè)function么,想知道這兩種寫法有什么區(qū)別
這和我之前所知的js的定義方法

function a (){
    ......
}

又有神馬不同呢

回答
編輯回答
不討喜

es6中的語法糖,
意思都是一樣的,只是寫法不同而已。
除了寫法不同,沒有(任何區(qū)別),
深入研究的話,就去研究箭頭函數(shù)中的this,this的用法和原始的有點(diǎn)差別。
如果你想問為什么要這樣寫,只能說這是語法糖,或者是個(gè)人習(xí)慣。

2017年7月27日 20:12
編輯回答
舊時(shí)光
class A extends React.Component{
    constructor(props){
        super(props)
    }
    componentDidMount(){
        dom.addEventListener('click', this.fnA)
        dom.addEventListener('click', this.fnB)
    }
    fnA(e){
        console.log(this)  //this指向dom節(jié)點(diǎn)
    }
    fnB = (e) => {
        console.log(this)  //this指向A
    }
}

區(qū)別還是有一點(diǎn)的,主要是this的問題。
舉個(gè)簡單的例子。
addEventListener綁定的回調(diào)函數(shù),以fnA(){}的寫法,this默認(rèn)綁定到監(jiān)聽器所在的DOM元素,即dom;如果需要正常訪問A,則需要bind綁定一下,改變回調(diào)函數(shù)的this指向。dom.addEventListener('click', this.fnA.bind(this))
fnB = (e) => {}的寫法是ES7的 property initializers。fnB初始化時(shí)就綁定好了this始終指向A。

2017年5月4日 14:11