简体   繁体   English

如何在 Typescript 中为现有的 JavaScript 模块模式编写模块模式

[英]How to write the Module Pattern in Typescript for an existing JavaScript Module Pattern

I am quite new to both Javascript and Typescript.我对 Javascript 和 Typescript 都很陌生。 I have to migrate the Javascript code into Typescript.我必须将 Javascript 代码迁移到 Typescript。 Here is a Module pattern that returns itself instead of exposing private methods and property (Please correct me If I am wrong).这是一个返回自身而不是公开私有方法和属性的模块模式(如果我错了,请纠正我)。 So I don't know how to deal with this situation.所以我不知道如何处理这种情况。

var MySocket = (function () {


    function MySocket(location, openCallback, closeCallback, errorCallback) {
        //Code Goes Here
    }



    MySocket.prototype.Open = function () {
        //Code Goes Here
    }

    MySocket.prototype.Close = function () {
        //Code Goes Here
    }



    return MySocket;
})();

This is called the revealing module pattern.这称为揭示模块模式。 You can still use this in TypeScript.你仍然可以在 TypeScript 中使用它。 The 'modern' pattern would be to remove the IIFE and return statement and instead add an export modifier to MySocket : “现代”模式是删除 IIFE 和return语句,而是向MySocket添加export修饰符:

export function MySocket(location, openCallback, closeCallback, errorCallback) {
   //Code Goes Here
}

MySocket.prototype.Open = function () {
  //Code Goes Here
}

MySocket.prototype.Close = function () {
  //Code Goes Here
}

However, the usage of this is slightly different.但是,this 的用法略有不同。 ES6 modules are expected to be imported from other ES6 modules using the import statement rather than just referring to the variable by name: ES6 模块应该使用import语句从其他ES6 模块import而不仅仅是通过名称引用变量:

import { MySocket } from './MySocket'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM