鍍金池/ 問答/HTML/ 一個(gè)ES6語法的疑惑

一個(gè)ES6語法的疑惑

最近在寫React,在定義一個(gè)class的方法時(shí),看到了如下fun1和fun2這兩種寫法,用起來都沒有問題??戳讼氯畲髱煹娜腴T指南,發(fā)現(xiàn)都是fun1這種寫法,那么這兩種寫法有啥區(qū)別呢?

class MyClass {
    name = 1;

    fun1() {
        console.log(this.name);
    }

    fun2 = () => {
        console.log(this.name);
    }
}
回答
編輯回答
櫻花霓
2018年8月5日 11:10
編輯回答
傻丟丟

fun2 = () => {

    console.log(this.name);
}
其實(shí)是
this.fun2 = () => {
    console.log(this.name);
}
吧 是自定義屬性 不是原型方法 這種定義屬性的方法目前也沒正式進(jìn)入規(guī)范 
2017年9月2日 20:33
編輯回答
傻丟丟

react用戶表示對第二種方式很熟悉

2018年9月16日 04:35
編輯回答
歆久

寫代碼最主要的是,實(shí)現(xiàn)功能即可。

這兩種寫法,你需要理解的只有兩點(diǎn),this的指向箭頭函數(shù)和普通函數(shù)this的區(qū)別。

1.普通函數(shù),this是在函數(shù)執(zhí)行時(shí)候才確定的。誰調(diào)用這個(gè)函數(shù),this指向誰,或者,手動call,apply指定this,或者bind生成一個(gè)指定了this的未調(diào)用函數(shù)。
2.箭頭函數(shù),this是在函數(shù)聲明的時(shí)候,代碼解析到聲明表達(dá)式的時(shí)候,這時(shí)候this是誰就是誰。類似于普通函數(shù)+bind。

應(yīng)用場景,個(gè)人覺得遇到的最多的情況,就是把A中有this的函數(shù)fn傳到別的地方,在非作用域?yàn)锳的情況下調(diào)用函數(shù)fn。這時(shí)候,可能你希望的是fn中的this指向的是A。這就需要你在A中聲明時(shí)候聲明成箭頭函數(shù),或者傳遞時(shí)候傳遞的是fn.bind(A)。

不只是React,我沒用過React。這個(gè)知識點(diǎn)應(yīng)該是js的語言特性,任何框架里面都是一樣的。

2017年11月2日 05:07
編輯回答
任她鬧

對于我這個(gè)偽前端來講,在定義方法的時(shí)候一般都是用fun1這個(gè)類型,為什么,因?yàn)榇a少,用的多,功能都能實(shí)現(xiàn);在導(dǎo)入組件及axios請求時(shí)都是用第fun2,為什么,因?yàn)槎际沁@樣用,因?yàn)橛行┕δ躥un1實(shí)現(xiàn)起來更復(fù)雜,也可能實(shí)現(xiàn)不了,具體什么兩個(gè)定義的差別可以看樓上的回答

2018年7月27日 20:12
編輯回答
骨殘心

this指向的問題:

this指向

React 組件書寫大多使用 class 構(gòu)造器寫成,這里的 this 指向需要確保綁定在 class 類所構(gòu)造出來的組件上面

1. bind 方法

 class Component3 extends React.Component {

    submit(e){
        console.log(this)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit3" onClick={this.submit.bind(this)}/>
    }
   
 }

2. 構(gòu)造器內(nèi)聲明

class Component2 extends React.Component {
   constructor(props) {
     super(props);
     this.submit = this.submit.bind(this);
   }

    submit(e){
        console.log(this)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit2" onClick={this.submit}/>
    }
   
 }

3.箭頭函數(shù)

class Component1 extends React.Component{
    submit(e){
        console.log(this)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit1" onClick={(e) => this.submit(e)}/>
    }
}

class Component4 extends React.Component{
    submit(e){
        console.log(this)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit" onClick={(e) => this.submit(e)}/>
    }
}
2017年1月20日 14:26
編輯回答
笑浮塵

第一種寫法沒有綁定this,第二種綁定了this;
如果沒經(jīng)過babel轉(zhuǎn)化,瀏覽器里面定義class時(shí)不能用第二種寫法,會報(bào)錯(cuò)Uncaught SyntaxError,

2018年5月21日 03:23