gpt4 book ai didi

javascript - 使用对象访问javascript中自调用函数的函数

转载 作者:行者123 更新时间:2023-11-30 20:20:20 26 4
gpt4 key购买 nike

我有一段代码的相同结构,想访问其他文件中定义的函数......我该怎么做,试过 module.exports & require

app.js

var x= require('./invkFunc1');

x.display1();
x.display2();
x.display3();

invkFunc1.js

var x = require('./invkFunc2');

(function(x){
//var x= {}
disp1 = "hello i am from display1"
x.display1 = function(){
console.log(disp1)
}
return x;
}(x));

invkFunc2.js

var x = require('./invkFunc3');

(function(x){
//var x= {}
x.disp2 = "hello i am from display2"
x.display2 = function(){
console.log(x.disp2)
}
return x;
}(x));

invkFunc3.js

module.exports = 

(function(){

var x= {}
x.disp3 = "hello i am from display3";
x.display3 = function(){

console.log(x.disp3)
}
return x;
}());

错误:

x.display1();
^

TypeError: x.display1 is not a function
at Object.<anonymous> (c:\Users\prabhat.mishra\Desktop\Chrome-DOM-EXT\extension as on 2rd july 2018\SampleExtension\module.exports\app.js:39:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3

我想从所有这些示例中了解,我如何访问较低级别的文件并使某些文件中定义的功能对存在的所有文件可用。
这样做是为了像以前一样通过将这些代码放在一个文件中来实现模块化,效果非常好。

工作代码::试图从下面代码的上面代码实现模块化

var x ={};



(function(){

// var x= {}
x.disp3 = "hello i am from display3";
x.display3 = function(){

console.log(x.disp3)
}
}());

(function(){
// var x= {}
x.disp2 = "hello i am from display2"
x.display2 = function(){
console.log(x.disp2)
}
console.log("call in invkFunc2");
//x.display3();
}());

(function(){
//var x= {}
x.disp1 = "hello i am from display1"
x.display1 = function(){
console.log(x.disp1)
}
}());

x.display1()
x.display2();
x.display3();

提前致谢!

最佳答案

如果你想使用“require”,你应该先导出,你可以这样编码

应用程序.js:

var x = require('./invkFunc1');

x.display1();
x.display2();
x.display3();

invkFunc1.js

var x = require('./invkFunc2');
var disp1 = "hello i am from display1"
x.display1 = function(){
console.log(disp1)
}
module.exports = x;

invkFunc2.js

var x = require('./invkFunc3');
var disp2 = "hello i am from display2"
x.display2 = function(){
console.log(disp1)
}
module.exports = x;

invkFunc3.js

var x = {}
x.disp3 = "hello i am from display3";
x.display3 = function () {
console.log(x.disp3)
}
module.exports = x;

关于javascript - 使用对象访问javascript中自调用函数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51515116/

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