gpt4 book ai didi

javascript - Node JS 说方法明显不存在

转载 作者:行者123 更新时间:2023-11-30 17:29:31 25 4
gpt4 key购买 nike

好的,所以我创建了一个测试项目来展示这个错误。错误是 Node JS 在我的另一个对象中找不到我的 getStr 函数。

这是代码:

测试.js

var Another = require('./another.js');
var Other = require('./other.js');

var otherStr = Other.getStr();

console.log(otherStr);

其他.js

var Another = require('./another.js');

var str = Another.getStr();

另一个.js

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com