javascript - 如何在nodejs中创建另一个javascript类的对象

标签 javascript node.js

您好,我想在另一个 index.js 文件中创建 ProfileComparator 对象,但出现错误。

strategy.js

var cosineUtils = require("./jscosine");

var ProfileComparator = function(algo, x, y, threshold) {
  this.algo = algo;
  this.x = x;
  this.y = y;
  this.threshold = threshold;
};

ProfileComparator.prototype.findMatches = function() {
  return this.algo(this.x, this.y, this.threshold);
};

var cosineAlgoStrategy = function(x, y, threshold) {
  var similarityCount = cosineUtils.cosineSimilarity(x, y);

  if (similarityCount >= threshold) {
    return y;
  }

  console.log("------------------------------------");
  console.log("cosine");
  console.log("------------------------------------");
};

var pearsonAlgoStrategy = function(x, y, threshold) {
  console.log("------------------------------------");
  console.log(threshold);
  console.log("------------------------------------");
};

我能够在 strategy.js 中创建 ProfileComparator 对象,而不是在其他 javascript 文件中创建对象,如下所示

var cosineAlgo = new ProfileComparator(cosineAlgoStrategy, "x", "y", 0.9);
return cosineAlgo.findMatches();

index.js

我试图在 index.js 中执行相同的操作,但我在这里收到错误:

var strategyUtils = require("./strategy");

function computeSimilarity(x, user) {
  var cosineAlgo = new ProfileComparator(cosineAlgoStrategy, x, y, 0.9);
  return cosineAlgo.findMatches();
}

堆栈跟踪:

ReferenceError: ProfileComparator is not defined
    at computeSimilarity (/user_code/index.js:187:24)
    at /user_code/index.js:232:16
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

有谁知道如何解决吗?

最佳答案

您需要像这样从 strategy.js 文件中导出 ProfileComparator 比较器函数

module.exports = ProfileComparator

在你的index.js中,像这样要求它

var ProfileComparator = require("./strategy");

关于javascript - 如何在nodejs中创建另一个javascript类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46026320/

相关文章:

javascript - NodeJS 模块函数约定——调用自己的函数

node.js - Nightwatch JS - 如何通过 Firefox headless 运行测试

javascript - 从 firebug 控制台调用自定义函数

javascript - Node.js 中的唯一事件监听器 ID

node.js - mosca MQTT 代理的安全 key 和证书

javascript - 无法在node js中使用post请求

java - IE 正在将 Controller 的响应作为文件

javascript - 编译函数显示自定义指令 angularJS 中的错误

javascript - 当选择要触发事件的行时,YUI 获取特定的单元格值

node.js - 比较 bcrypt 中两个相同的字符串哈希返回未定义