Nodejs设置一个全局函数并调用一个嵌套函数



我的主要功能

import AppLauncher from './Applauncher'
function Mainfunc() {
global.app=  AppLauncher()
global.app.start('index')
}

AppLauncher.js

function AppLauncher() {
function start(opts){
console.log('functions start called with' + opts)
}
}
export default AppLauncher

我想将AppLauncher函数分配为全局函数,并调用嵌套在其中的启动函数

构造函数是我们要走的路。你可以这样做:

// AppLauncher.js
function AppLauncher() {
// run some code...
// notice `this`
this.start = function(opts) {
console.log('start function called with', opts);
}
}
export default AppLauncher;

在主函数中,使用new关键字调用它:

import AppLauncher from './AppLauncher';
function Mainfunc() {
global.app = new AppLauncher();
global.app.start('index');
}

构造函数也可以写成类(你可以像我上一个例子一样使用它(:

class AppLauncher {
constructor() {
// Anything in here gets executed when once you create an object from this class with the `new` keyword
}
// Instead of `this` we add a method to the class:
start(opts) {
console.log('start function called with', opts);
}
}
export default AppLauncher;

有关构造函数的详细信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

如果你不想使用构造函数,你也可以返回一个对象:

// AppLauncher.js
function AppLauncher() {
// Some code here...
return {
start(opts) {
console.log("function start called with", opts);
}
};
}
export default AppLauncher;

你可以像你想的那样使用这个:

import AppLauncher from `./AppLauncher`;
function Mainfunc() {
global.app = AppLauncher();
global.app.start('index');
}

顺便说一句,通常使用PascalCase调用构造函数,而使用camelCase调用常规函数。

最新更新