- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
好的,所以我创建了一个测试项目来展示这个错误。错误是 Node JS 在我的另一个对象中找不到我的 getStr 函数。
这是代码:
var Another = require('./another.js');
var Other = require('./other.js');
var otherStr = Other.getStr();
console.log(otherStr);
var Another = require('./another.js');
var str = Another.getStr();
var Other = require('./other.js');
var str = "other String";
exports.getStr = function(){
return str;
}
这是我的输出:
C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test>node test.js
C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\other.js:3
var str = Another.getStr();
^
TypeError: Object #<Object> has no method 'getStr'
at Object.<anonymous> (C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\ot
her.js:3:19)
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)
at Object.<anonymous> (C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\an
other.js:1:75)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test>
那么如何让 Node JS 在 Other 中看到 Another 的 getStr 函数呢?
最佳答案
您在这里处理的是循环依赖。 Node.js 将让您以循环方式加载模块,但您需要设计您的代码来解决它。 一般来说,循环依赖是设计存在缺陷的标志。在问题中显示的代码中,another
需要other
但什么也不做。因此,最简单的解决方法是更改 another
,这样它就不需要 other
。
如果您出于某种原因必须保留循环依赖,或者您想出于学习目的试验循环依赖,那么这将是另一种可能的解决方法:
var str = "other String";
exports.getStr = function(){
return str;
}
var Other = require('./other');
// Actually do something with Other down here.
当 other
被要求时,another
将至少有 getStr
可用。所以这会解决眼前的问题。但是请注意,您的 other
模块不会导出任何内容,因此您的 test.js
文件仍然会在 var otherStr = Other.getStr();
处失败可能你忘了添加这个:
exports.getStr = function(){
return str;
}
(注意:我已经修改了 require
调用,因此它需要 other
而没有 .js
后缀。通常,您不需要不想在您的 require
调用中添加后缀。您想添加一个 Node 可以解析为文件、包或其他内容的模块名称。)
关于javascript - Node JS 说方法明显不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23439671/
通常当我请求线程转储时,系统性能不佳的症状很容易解释;也就是说,通常我会看到许多线程显然正在等待一个已被获取但未被另一个释放的监视器。 在这种情况下,我有很多线程在等待监视器 (0x965ad100)
C:\Users\shagy\Desktop\3RD YEAR 2ND SEMESTER\SPM\Newfolder\SPM-SMS>npm start npm ERR! path C:\Users\
我是一名优秀的程序员,十分优秀!