一个ES6语法的疑惑

最近在写React,在定义一个class的方法时,看到了如下fun1和fun2这两种写法,用起来都没有问题。看了下阮大师的入门指南,发现都是fun1这种写法,那么这两种写法有啥区别呢?

class MyClass {
    name = 1;

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

    fun2 = () => {
        console.log(this.name);
    }
}
阅读 3.2k
7 个回答

fun2 = () => {

    console.log(this.name);
}
其实是
this.fun2 = () => {
    console.log(this.name);
}
吧 是自定义属性 不是原型方法 这种定义属性的方法目前也没正式进入规范 

第一种写法没有绑定this,第二种绑定了this;
如果没经过babel转化,浏览器里面定义class时不能用第二种写法,会报错Uncaught SyntaxError,

this指向的问题:

this指向

React 组件书写大多使用 class 构造器写成,这里的 this 指向需要确保绑定在 class 类所构造出来的组件上面

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. 构造器内声明

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.箭头函数

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)}/>
    }
}

对于我这个伪前端来讲,在定义方法的时候一般都是用fun1这个类型,为什么,因为代码少,用的多,功能都能实现;在导入组件及axios请求时都是用第fun2,为什么,因为都是这样用,因为有些功能fun1实现起来更复杂,也可能实现不了,具体什么两个定义的差别可以看楼上的回答

写代码最主要的是,实现功能即可。

这两种写法,你需要理解的只有两点,this的指向箭头函数和普通函数this的区别

1.普通函数,this是在函数执行时候才确定的。谁调用这个函数,this指向谁,或者,手动call,apply指定this,或者bind生成一个指定了this的未调用函数。
2.箭头函数,this是在函数声明的时候,代码解析到声明表达式的时候,这时候this是谁就是谁。类似于普通函数+bind。

应用场景,个人觉得遇到的最多的情况,就是把A中有this的函数fn传到别的地方,在非作用域为A的情况下调用函数fn。这时候,可能你希望的是fn中的this指向的是A。这就需要你在A中声明时候声明成箭头函数,或者传递时候传递的是fn.bind(A)。

不只是React,我没用过React。这个知识点应该是js的语言特性,任何框架里面都是一样的。

react用户表示对第二种方式很熟悉

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题