TypeScript code similar to Revealing Module Pattern structure

こ雲淡風輕ζ 提交于 2020-01-02 06:19:27

问题


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.

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.

One example is the below:

//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?


回答1:


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) {
    }
}


来源:https://stackoverflow.com/questions/29275307/typescript-code-similar-to-revealing-module-pattern-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!