简体   繁体   English

如何在我的方法和TypeScript接口中将类设为私有?

[英]How can I make a class private in my method and interface with typescript?

I have a class in my application 我的申请中有课程

class MyClass {
    doTask1 = () => {
        doTask2();
    }
    doTask2 = () => {

    }
}

How can I set up an interface file and how do I decorate my methods for this so that doTask1 is public and doTask2 is private? 如何设置接口文件,以及如何为此装饰方法,以便doTask1是公共的而doTask2是私有的?

How can I set up an interface file 如何设置界面文件

Javascript does not strictly have interfaces, see this stack overflow question JavaScript严格没有接口, 请参见此堆栈溢出问题

how do I decorate my methods for this so that doTask1 is public and doTask2 is private? 如何为此装饰我的方法,以便doTask1是公共的而doTask2是私有的?

In Javascript, the idea of public and private is sort of not there, although many people follow the convention of appending and underscore to the variable or function name (such as _foo ) to let others know it was meant to be private. 在Javascript中,虽然很多人遵循在变量或函数名称后加下划线的约定(例如_foo ),以使其他人知道它是私有的,但public和private的概念并不存在。 However, you can control access to variables, here is a good explanation of that written by Douglas Crockford. 但是,您可以控制对变量的访问, 这是 Douglas Crockford所写的很好的解释

EDIT 编辑

For TypeScript specifically, I'd checkout out the MSDN article on interfaces , and I think that this stack overflow question is relevant to your question about private functions. 特别是对于TypeScript,我将签出有关interfacesMSDN文章 ,并且我认为此堆栈溢出问题与您有关私有函数的问题有关。

Remember - Interfaces can only contain public methods: 记住-接口只能包含公共方法:

interface IMyClass {
    doTask1(): void;
}

class MyClass implements IMyClass {
    doTask1 = () => {
        this.doTask2();
    }
    doTask2 = () => {

    }
}


var instance: IMyClass = new MyClass();
instance.doTask1(); // Ok
instance.doTask2(); // Error 

Runnable Example: http://bit.ly/Uzkv7V 可运行的示例: http : //bit.ly/Uzkv7V

Btw, You should probably structure your class like this: 顺便说一句,您可能应该像这样构造您的类:

class MyClass implements IMyClass {
    doTask1() {
        this.doTask2();
    }
    private doTask2() {

    }
}

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

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