节点js:定义实体类的最佳方式

时间:2017-10-29 23:23:09

标签: node.js entity-framework

我正在节点js中编写一个工具。我想在节点js中定义一些POJO。我没有很多Node js的经验。我来自JAVA背景,其中类用于定义实体。我现在定义实体的一种方法是: -

function Person(name) {
    this.name = name;
    this.values = [];
    this.characteristics = {};
}

但这是在一个JS文件中定义的。为了使其在其他JS文件中可用,我必须导出此函数。这是定义实体的最佳方式还是有任何其他方式可以定义类格式?

1 个答案:

答案 0 :(得分:2)

这对于创建对象很好。如果您开始使用像mongo这样的数据库,那么最好还是创建具有猫鼬的对象,但这也是个人偏好。至于你的例子 -

1)出口人

tidy_df %>%
  gather(variable, value, a, b, d) %>%
  unite(level_variable, level, variable) %>%
  spread(level_variable, value)

#> # A tibble: 26 x 12
#>       ID        p         c     high_a     high_b     high_d      low_a
#>  * <chr>    <dbl>     <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
#>  1     a 358.8198 0.3517979 0.54406602 0.79892485  79.011379 0.54406602
#>  2     b 809.4746 0.1111354 0.59414202 0.12189926   9.382306 0.59414202
#>  3     c 468.0792 0.2436195 0.28915974 0.56094798  26.635096 0.28915974
#>  4     d 894.7157 0.6680556 0.14711365 0.20653139  26.151654 0.14711365
#>  5     e 946.4206 0.4176468 0.96302423 0.12753165  69.905442 0.96302423
#>  6     f 141.0008 0.7881958 0.90229905 0.75330786 108.778072 0.90229905
#>  7     g 575.2949 0.1028646 0.69070528 0.89504536  52.681362 0.69070528
#>  8     h 903.1771 0.4348927 0.79546742 0.37446278 168.480110 0.79546742
#>  9     i 596.2915 0.9849570 0.02461368 0.66511519  13.845603 0.02461368
#> 10     j 510.9533 0.8930511 0.47779597 0.09484066  29.775361 0.47779597
#> # ... with 16 more rows, and 5 more variables: low_b <dbl>, low_d <dbl>,
#> #   med_a <dbl>, med_b <dbl>, med_d <dbl>

2)从另一个文件导入人

module.exports = Person;

3)使用const Person = require('../path/to/Person'); 关键字创建Person以调用构造函数(非常重要)

new

您应该阅读const mitch = new Person('Mitch'); 。每个对象都引用javascript's prototype。然后,您可以使用Object.prototype创建对象来创建对象,并将新对象的原型指定为传递给Object.create(obj)

的引用

Here's an example from MDN

Object.create(obj)