繁体   English   中英

使用node.js导出类

[英]Exporting classes with node.js

我有一个名为bob_test.spec.js的文件中由jasmine-node运行的以下测试代码

require('./bob');

describe("Bob", function() {
  var bob = new Bob();

  it("stating something", function() {
    var result = bob.hey('Tom-ay-to, tom-aaaah-to.');
    expect(result).toEqual('Whatever');
  });
});

为了使测试通过,我在一个名为bob.js的文件中编写了以下生产代码

"use strict";

var Bob = function() {
}

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

module.exports = Bob;

当我运行测试时 - 使用jasmine-node . - 我得到以下F

Failures:

1) Bob encountered a declaration exception
Message:
    ReferenceError: Bob is not defined
Stacktrace:
    ReferenceError: Bob is not defined
    at null.<anonymous> (/Users/matt/Code/oss/deliberate-practice/exercism/javascript/bob/bob_test.spec.js:4:17)
    at Object.<anonymous> (/Users/matt/Code/oss/deliberate-practice/exercism/javascript/bob/bob_test.spec.js:3:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)

Finished in 0.02 seconds
1 test, 1 assertion, 1 failure, 0 skipped

基于我对Javascript的理解,我觉得这应该有效。 node.js对构造函数和模块导出做了哪些不同的事情阻止了它的工作我认为应该这样做?

require返回一个对象,你应该将它存储在某个地方

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

然后使用此对象

var bobInstance = new Bob();

如果您可以使用ECMAScript 2015,您可以声明并导出您的类,然后使用解构“导入”您的类,而无需使用对象来获取构造函数。

在模块中,您可以像这样导出

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

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

module.exports = {
    Person,
    Animal
};

然后你在哪里使用它们

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

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

这应该可以解决您在通过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);

改善马文的答案:

"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');

所以你可以创建一个将它传递给module.exports的对象module.exports = new Bob();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM