我查看了一些与此错误相关的问题,其中大部分似乎是对关键字this
含义的误解。我不认为我在这里有这个问题。我的可能是某种循环依赖问题,我无法很好地表达出来,无法自己解决。
我试图将我的问题提炼成下面显示的三个文件。
var A = require('../lib/a');
var Something = function (type) {
this.type = type;
};
Something.prototype.setTemplate = function (template) {
this.template = template;
};
Something.prototype.applyTemplate = function () {
var templateResult = this.template.calculate();
};
var factory = {};
factory.createSomething = function(type) {
return new Something(type);
};
factory.createA = function (input) {
return A.Make(input);
};
module.exports = factory;
var S = require('../prof/something');
var _ = require('underscore');
var A = function (input) {
this.input = input;
};
A.prototype.calculate = function () {
var calculation = 0;
var _s = S.createSomething('hello world');
// do calculation using input
return calculation;
};
var factory = {};
factory.Make = function (input) {
var a = new A(input);
return a;
};
module.exports = factory;
describe('Unit: A Test', function() {
var S = require('../prof/something');
it('test 1', function() {
var a = S.createA({
//input
});
var s = S.createSomething('type1');
s.setTemplate(a);
s.applyTemplate(); // error
});
});
错误从a_test.js
带有注释的行的顶层抛出//error
。在最低级别,“不是函数”错误是在方法中抛出a.js
的S.createSomething(type)
。它说这S.createSomething()
不是一个函数。
我在该行放置了一个断点并尝试从下划线库调用函数,但它给出了相同的错误。所以看起来里面的require语句a.js
没有抛出错误,但是没有一个注入的对象可以用来调用函数。该a_test.js
文件正在与 karma 库一起运行。
通过在 A 和 S 之间来回引用,我是否违反了一些 javascript 范式?我怎样才能正确地做到这一点?
编辑:我做了一些进一步的测试。测试文件是否如下所示实际上并不重要:
describe('Unit: A Test', function() {
var S = require('../prof/something');
it('test 1', function() {
var a = S.createA({
//input
});
a.calculate(); // error
});
});
上面指示的行仍然会抛出错误。
问题中的文件相互引用。这称为循环依赖。解决方案是将var S = require('../prof/something');
语句移动到计算函数中,如下所示:
// move the line from here
var _ = require('underscore');
var A = function (input) {
this.input = input;
};
A.prototype.calculate = function () {
var S = require('../prof/something'); // to here
var calculation = 0;
var _s = S.createSomething('hello world');
// do calculation using input
return calculation;
};
var factory = {};
factory.Make = function (input) {
var a = new A(input);
return a;
};
module.exports = factory;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句