【问题标题】:Accessing a function declares in a class in Javascript ES6 (ES2015? ES16?)访问函数在 Javascript ES6 中的类中声明(ES2015?ES16?)
【发布时间】:2016-04-05 02:17:07
【问题描述】:

我创建了一个小助手类:

import moment from 'moment';

export default class Format {
  formatDate(date) {
    return moment(date);
  }
}

我正在尝试在 JSX 模板中调用它:

import React from 'react';
import Format from '/imports/helpers/format.js';

export default class ListingCard extends React.Component {
  render() {
    return (
      <div className="card">        
        {Format.formatDate(this.props.listing.created_at)}</div>
      </div>
    )
  }
}

使用 WebStorm,找到 Format 类。但方法不是。

ListingCard.jsx:22 Uncaught TypeError: _format2.default.formatDate 不是函数

知道为什么吗?

【问题讨论】:

  • Format.prototype.formatDate 是函数。 class 是原型的糖。
  • “我创建了一个小助手类:” 你不应该为此使用一个类。只需导出函数:export default function formatDate() {}。或者如果你有更多这样的功能:export function formatDate() {}.

标签: javascript function class ecmascript-6


【解决方案1】:

您需要使用static 关键字来声明一个类方法

export default class Format {
  static formatDate(date) {
    return moment(date);
  }
}

原因是,如果不使用static 关键字,formatDate 将是一个实例方法,这意味着该方法仅适用于实例 em> 的班级。

// e.g., how to use an instance method
var f = new Format();
f.formatDate(someDate);

@loganfsmyth 说得很好;这是我最初的答案中没有考虑到的问题。

如果您不打算将Format 用作一个类,那么声明它是没有意义的。

// format.js
import moment from 'moment'
export function formatDate(date) { return moment(date); }

// otherfile.js
import {formatDate} from './format';

【讨论】:

  • 比起使用prototype,我更喜欢这种方法。这是有道理的。
  • @SergioTapia 不要自欺欺人。 class 仍然使用原型。类方法和实例方法适用于不同的设计。它们都同样有用。 class 只是隐藏了一些丑陋的 prototype 语法。
  • 如果你只是存储一组函数,你还不如做export function formatDate(){}import {formatDate} from '...';而不使用类。
猜你喜欢
  • 1970-01-01
  • 2018-06-06
  • 2016-06-06
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
  • 2017-03-11
  • 2018-11-04
  • 1970-01-01
相关资源
最近更新 更多