Exporting classes with node.js

橙三吉。 提交于 2019-11-28 18:13:39
mrvn

require returns an object, you should store it somewhere

var Bob = require('./bob');

and then use this object

var bobInstance = new Bob();

If you can use ECMAScript 2015 you can declare and export your classes and then 'import' your classes using destructuring with no need to use an object to get to the constructors.

In the module you export like this

class Person
{
    constructor()
    {
        this.type = "Person";
    }
}

class Animal{
    constructor()
    {
        this.type = "Animal";
    }
}

module.exports = {
    Person,
    Animal
};

then where you use them

const { Animal, Person } = require("classes");

const animal = new Animal();
const person = new Person();

This should fix the error you were having while running your tests via jasmine-node:

// Generated by CoffeeScript 1.6.2
(function() {
  var Bob;

  Bob = (function() {
    function Bob() {}

    Bob.prototype.hey = function(what) {
      return 'Whatever.';
    };

    return Bob;

  })();

  module.exports = Bob;

}).call(this);
Novitoll

Improving marvin's answer:

"use strict";
var Bob = function() {}

Bob.prototype.hey = function (text) {
  return "Whatever";
}

module.exports = new Bob();

// another file
var Bob = require('./bob');
Bob.hey('text');

So you can create an object passing it to module.exports module.exports = new Bob();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!