使用 node.js 导出类

Exporting classes with node.js(使用 node.js 导出类)
本文介绍了使用 node.js 导出类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个名为 bob_test.spec.js

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

In order to make the test pass, I've written the following production code in a file called bob.js

"use strict";

var Bob = function() {
}

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

module.exports = Bob;

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

When I run the test - using jasmine-node . - I get the following 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 与构造函数和模块导出有什么不同,阻止它工作我认为它应该?

Based on what I understand about Javascript, I feel like this should work. What does node.js do differently with constructor functions and module exports that prevents this from working I like think it should?

推荐答案

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

require returns an object, you should store it somewhere

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

然后使用这个对象

var bobInstance = new Bob();

这篇关于使用 node.js 导出类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)