构造函数是要走的路。你可以这样做:
// AppLauncher.js
function AppLauncher() {
// run some code...
// notice `this`
this.start = function(opts) {
console.log('start function called with', opts);
}
}
export default AppLauncher;
在您的 main 函数中,使用以下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
。