TypeScript代码类似于Revealing Module Pattern结构 [英] TypeScript code similar to Revealing Module Pattern structure

查看:88
本文介绍了TypeScript代码类似于Revealing Module Pattern结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我编写的一些JavaScript代码转换为TypeScript。作为一名JavaScript开发人员,我对TypeScript语法和思维方式都很陌生。

I want to convert some JavaScript code I've written into TypeScript. I'm rather new to TypeScript syntax and way of thinking, as a JavaScript developer.

令我头疼的是我很难转换一些将显示模块模式用于TypeScript的代码片段。

What is giving me a headache is the hard time I've had to convert some piece of code that uses the Revealing Module Pattern into TypeScript.

以下是一个例子:

//JS Code
var obj;

//code...
(function(){
    function myFunction(){
        //do work
    }


    function MyOtherConstructor(){
        return {
            publicMethod: myFunction
        }
    }

    obj = new MyOtherConstructor();
})();

//use obj.publicMethod in code later

一个解决方法我'我想是这样的:

One workaround I've thought was this:

//TypeScript code
var obj;

class MyOtherConstructor {
        private callback: any;
        constructor(f: any){
            this.callback = f;
        }
        publicMethod(): any{
            this.callback();
        }
}
//code...
(() => {
    function myFunction(){
        //do work
        console.log("Called myFunction");
    }
    obj = new MyOtherConstructor(myFunction);
})();

//use obj.publicMethod in code later

哪个有效,但是这很难看。

which works, but it's ugly.

有什么建议让这更好吗?

Any suggestion how make this better?

推荐答案

如果您需要单个对象 obj ,则不要使用类。命名空间更适合:

If you need a single object obj, then do not use a class. A namespace is more adapted:

namespace obj {
    function myFunction() {
        // ...
    }
    export var publicMethod = myFunction;
}






如果您愿意保留该类,然后这是一个更简洁的代码:


If you prefer to keep the class, then here is a more concise code for it:

class MyOtherConstructor {
    constructor(public publicMethod: () => void) {
    }
}

这篇关于TypeScript代码类似于Revealing Module Pattern结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆