React中普通函数与箭头函数的区别

React 中 普通函数 get(){} 与 箭头函数 get=()=>{} 的区别。

补充阅读: JavaScript和React中的箭头函数 - 编程技术 - CEPD@BBS

1. 语法定义

get(){}

  • 是 ES6 中的方法定义语法
  • 定义在类的原型(prototype)上
  • 传统的类方法定义方式

get=()=>{}

  • 是类属性(Class Fields)语法(Stage 3 提案)
  • 使用箭头函数定义
  • 实例属性,绑定到每个实例

2. this 绑定行为

get(){}

  • this 动态绑定:取决于调用方式
  • 需要手动绑定(如 constructor 中绑定或使用箭头函数包装)
class Example {
  constructor() {
    this.value = 'test';
    // 需要手动绑定
    // this.get = this.get.bind(this);
  }
  
  get() {
    console.log(this.value); // this 可能为 undefined
  }
}

get=()=>{}

  • this 静态绑定:始终指向类实例
  • 自动绑定,无需额外处理
class Example {
  value = 'test';
  
  get = () => {
    console.log(this.value); // this 始终指向实例
  }
}

3. 内存使用

get(){}

  • 共享方法:所有实例共享同一个方法
  • 内存效率更高
class Example {
  get() {}
}

const obj1 = new Example();
const obj2 = new Example();
console.log(obj1.get === obj2.get); // true

get=()=>{}

  • 独立方法:每个实例都有自己的方法副本
  • 内存占用更大
class Example {
  get = () => {}
}

const obj1 = new Example();
const obj2 = new Example();
console.log(obj1.get === obj2.get); // false

4. 性能比较

方面 get(){} get=()=>{}
创建速度 更快 较慢(每个实例都要创建新函数)
调用速度 稍快 稍慢
内存占用 更少 更多

5. 在 React 组件中的应用

类组件中的使用

// 方式一:原型方法
class MyComponent extends React.Component {
  handleClick() {
    // 需要处理 this 绑定
    console.log(this.props);
  }
  
  render() {
    return <button onClick={this.handleClick.bind(this)}>Click</button>;
  }
}

// 方式二:箭头函数属性
class MyComponent extends React.Component {
  handleClick = () => {
    // this 自动绑定
    console.log(this.props);
  }
  
  render() {
    return <button onClick={this.handleClick}>Click</button>;
  }
}

推荐做法

class MyComponent extends React.Component {
  // 对于事件处理程序,推荐使用箭头函数
  handleClick = () => {
    // 自动绑定 this
  }
  
  // 对于其他方法,可以使用传统方法
  calculateData() {
    // 如果不需要作为回调,可以使用这种方式
  }
  
  // 或者在 constructor 中绑定
  constructor(props) {
    super(props);
    this.calculateData = this.calculateData.bind(this);
  }
}

6. 继承行为

get(){}

  • 支持方法重写
  • 可以通过 super 调用父类方法
class Parent {
  get() {
    return 'parent';
  }
}

class Child extends Parent {
  get() {
    return super.get() + ' child';
  }
}

get=()=>{}

  • 难以重写
  • 不是真正的类方法,而是实例属性
class Parent {
  get = () => 'parent';
}

class Child extends Parent {
  // 很难重写父类的 get 方法
  get = () => {
    // 无法调用 super.get()
    return 'child';
  }
}

7. 总结对比表

特性 get(){} get=()=>{}
this 绑定 动态绑定 静态绑定
内存使用 共享,更高效 独立,占用更多
性能 创建快,调用快 创建慢,调用稍慢
继承支持 完整支持 有限支持
可读性 标准语法 较新语法
React 事件处理 需要手动绑定 自动绑定

8. 最佳实践建议

  1. 事件处理程序:使用 get = () => {} 避免绑定问题
  2. 普通方法:使用 get(){} 节省内存
  3. 需要继承的方法:使用 get(){} 保持继承链完整
  4. 性能敏感场景:优先考虑 get(){} 减少内存占用

根据具体需求选择合适的语法,在 React 组件中通常混合使用两种方式以达到最佳效果。