TypeScript 全局调用

前言

export default class Loading extends cc.Component {
    
    
    private registerNode = null;
    private loginViewNode = null;

    showRegister() {
    
    
        if (this.registerNode == null) {
    
    
            this.registerNode = cc.instantiate(this.registerView);
            this.node.addChild(this.registerNode);
            this.registerNode = this.registerNode.getComponent(RegisterView);
        }
        this.registerNode.show();
    }
}

假设我有一个Loading类,我希望showRegister()方法可以全局被其他类调用。

Window

直接挂在 window 上。

1.直接赋值

//赋值this=Loading
window["gloading"] = this;

//调用
window["gloading"].showRegister();

2.声明 d.ts

新建一个xxx.d.ts文件,添加如下代码。

//必须是Window
declare interface Window {
    
    
    loading: any;
}
//赋值this=Loading
window.loading = this;

//调用
window.loading.showRegister();

global

直接挂在 global 上,可以不声明直接赋值调用。

//赋值this=Loading
global.loading = this;

//调用
global.loading.showRegister();

静态

直接声明一个静态变量,或者将showRegister改为静态函数。

export default class Utils {
    
    
    public static loading: Loading;
}
//赋值this=Loading
Utils.loading = this;

//调用
Utils.loading.showRegister();

namespace

export namespace Global {
    
    
    export let loading: Loading;
}
//赋值this=Loading
Global.loading = this;

//调用
Global.loading.showRegister();

猜你喜欢

转载自blog.csdn.net/DeMonliuhui/article/details/128646540