类方法是否可以在 ES 6 或 7 中声明为引用

Can class methods be declared as a reference in ES 6 or 7?

本文关键字:声明 引用 是否 ES 类方法      更新时间:2023-09-26

我试图从react-redux-universal-hot-example中掌握这段代码(我的上帝,看看我们走了多远!

无论如何。。

他们为一个类声明了 2 个静态方法,作为对 2 个函数参数的引用。

export default function connectData(fetchData, fetchDataDeferred) {
  return function wrapWithFetchData(WrappedComponent) {
    class ConnectData extends Component {
      static fetchData = fetchData;
      static fetchDataDeferred = fetchDataDeferred;
      render() {
        return <WrappedComponent {...this.props} />;
      }
    }
    return ConnectData;
  };
}

关键是..这行得通...但是 ES6 或 ES7 是否支持它?你能实现一个类成员作为你作为参数接收的东西的引用吗?

根据

ClassElement的语法,它不是有效的ES6,并且在尝试ES6 REPL时失败:

const method = () => {};
class Example { static _method = method; }
//=> Unexpected token (2:31)

。但建议用于 ES7+,这可能是 babel 插件实现的功能。

为什么不呢?本质上,他们返回以下内容:

return {
  fetchData         : fetchData,
  fetchDataDeferred : fetchDataDeferred,
  render            : function()  {...},
  __proto__         : Component 
};

不完全是,但从概念上讲,它足够接近......