JavaScript下导出Export和Import引入JS方法属性

本文介绍了JavaScript中如何导出和导入函数及类的方法,包括静态方法的获取与实例化,以及全局变量的导出和使用。示例中展示了HelloWorld()函数、HelloAccenture()静态方法和全局变量num001的导出与在其他JS文件中的调用方式。
摘要由CSDN通过智能技术生成

如题,记录一下JS下共通方法的定义导出,方便一些其他JS文件的调用,HelloWorld()方法写在类外,可以直接Export,HelloAccenture()方法写在基类内,需要获取到类New对象,才可以导出。全局变量num001可直接导出,在其他js读取。

var num001 = 100;

function HelloWorld() {
    console.log('Hello World!');
}

class Util {
    /**
    * Get an instance of subClass
    */
    static getInstance(subClassInstance) {
        //debugger
        if (!subClassInstance.instance) {
            subClassInstance.instance = new subClassInstance();
            return subClassInstance.instance;
        }
        return subClassInstance.instance;
    }
}

class Hello extends Util {
    /**
    * Get an instance of DataTable
    * @static
    * @returns {Hello} An instance of DataTable
    * */
    static getInstance() {
        return super.getInstance(Hello);
    }
    HelloAccenture() {
        console.log('Hello Accenture!');
    }
}

function getProperties(targetClass) {
    return targetClass.getInstance();
}

//根据new类对象,导出类内的方法供外界调用
export const { HelloAccenture } = getProperties(Hello);

//也可以直接new类导出类方法
//export const { HelloAccenture } = new Hello();

//直接导出写在类外的方法属性等
export default {
    num001, HelloWorld,
};

在某一个页面处调用的代码,导出num001处也可以不加default,调用处就省去了default,直接hello.num001。

$(document).ready(initialize());

async function initialize() {
    debugger
    window.hello = await import("/Areas/TEGCDebitAndCreditBalance/Scripts/hello.js");
    hello.default.HelloWorld();
    hello.HelloAccenture();
    console.log(hello.default.num001);
}
	

运行结果:

 

仅供学习参考,如有侵权联系我删除

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值