gpt4 book ai didi

javascript - node.js 文件中的单独函数

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

我想在我的 node.js 文件中分离函数。我不知道该怎么做。

这是一个例子:

    var var1 = 'I want to use this var along across all included files';
var var2 = 'I want to use this var along across all included files';
var actions = {
send1() { //function 1 with var1 & var2 },
send1a() { //function 1a with var1 & var2},
send2() { //function 2 with var1 & var2},
send2a() { //function 2a with var1 & var2}
};

我想在 function1.jssend2() 中导出 send1() & send1a() & function2.js 中的 send2a() 以获得干净的文件并使用 var1 & var2

我怎样才能正确地做到这一点?

最佳答案

创建 2 个模块文件:fun1.js

var var1 = "CONSTANT"


var actions = {
// Whatever you want to export, you can write it here
send1: function () {
console.log("send1", var1)
},
send1a: function () {
console.log("send1a")
},
a: "asdsad",
b: 45,
c: [1, 2, 3, 4, 5, 6],
var1: var1
}


module.exports = actions

/*
Or you can export using
module.exports = {
actions: actions,
variableX: "something"
}

then in other modules, import it as
var fun = require('./module_path')

And use it as fun.variableX, fun.actions.send1 etc
*/

fun2.js

// Import variable from other module
var fun1 = require('./fun1')
// or just import var1
// var var1 = require('./fun1').var1

var actions = {
send2: function () {
console.log("send2", fun1.var1)
},
send2a: function () {
console.log("send2a")
}
}


module.exports = actions

然后在主文件中

主要.js

// Import all modules
var fun1 = require('./fun1')
var fun2 = require('./fun2')

console.log(fun1.a) // Prints array

// fun1 will have all exported modules from fun1.js file
fun1.send1() // Prints send1 CONSTANT
fun1.send1a()

// fun2 will have all exported modules from fun2.js file
fun2.send2() // Prints send2 CONSTANT
fun2.send2a()

关于javascript - node.js 文件中的单独函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43704826/

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