You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

模块调用时如何自动执行方法且保留其他可调用方法?

解决方案

当然可以实现,下面提供几种符合需求的写法:

方式一:改造现有工厂函数(最贴近原写法)

直接在工厂函数内部自动执行目标方法,同时返回包含所有方法的对象:

export default () => {
  const init = () => {
    alert('hello');
  };
  
  // 自动执行init方法
  init();

  return {
    init,
    // 新增其他方法
    logMessage() {
      console.log('这是额外的方法');
    },
    calculate(num) {
      return num * 2;
    }
  };
};

调用时只需执行:

import Test from './Test';
let test = Test(); // 自动弹出hello
test.logMessage(); // 调用其他方法

方式二:构造函数模式

用传统构造函数实现,同时确保调用时无需new也能正常工作:

export default function Test() {
  // 构造时自动执行的逻辑
  alert('hello');

  // 挂载实例方法
  this.init = function() {
    console.log('可手动调用的init方法');
  };
  this.fetchData = function() {
    console.log('模拟获取数据');
  };
}

调用时可以用两种方式:

import Test from './Test';
// 方式1:用new调用
let test = new Test(); 
// 方式2:直接调用(需确保构造函数内部逻辑不受this指向影响)
let test = Test();
test.fetchData(); // 调用其他方法

方式三:ES6类包装

用类来组织方法,通过工厂函数隐式创建实例,保持原调用方式:

export default () => {
  class TestModule {
    constructor() {
      // 实例化时自动执行
      alert('hello');
    }

    init() {
      console.log('手动调用init');
    }

    handleEvent() {
      console.log('处理事件的方法');
    }
  }

  return new TestModule();
};

调用方式和原写法一致:

import Test from './Test';
let test = Test(); // 自动弹出hello
test.handleEvent(); // 调用其他方法

内容的提问来源于stack exchange,提问作者panthro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:25:18