您好,我想在另一个 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/