typescript 在打字稿中创建类的新实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42222533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a new instance of a class in typescript
提问by Nicolas
I'm trying to create a new instance of a class, with empty values but I'm struggling with the code.
我正在尝试使用空值创建一个类的新实例,但我正在努力编写代码。
Here's my class file code:
这是我的类文件代码:
export class MyTimeDefinition {
RequestCodes: Array<RequestCodes>;
BalanceCodes: Array<BalanceCodes>;
ID: number;
Description: {
SelectedLanguage: number,
Values: {
LanguageID: number,
ValueID: number,
Value: string
}[]
};
IsDataLoaded: boolean;
TypeName: string;
}
export interface RequestCodes {
ID: number;
StringValue: string;
}
export interface BalanceCodes {
ID: number;
StringValue: string;
}
and in my component I try to create a new instance of the class like this:
在我的组件中,我尝试创建类的新实例,如下所示:
//Create New MyTime-Definition
public createNewMyTimeDefinition() {
let newMyTimeDefinition = new models.MyTimeDefinition();
console.log(newMyTimeDefinition);
}
the result of my console.log is MyTimeDefinition {}
how can I create the variable newMyTimeDefinitionthat has all the attributes of the class and not just an empty object?
我的 console.log 的结果是MyTimeDefinition {}
如何创建具有类的所有属性而不仅仅是空对象的变量newMyTimeDefinition?
采纳答案by Tinwor
You must create a constructor
in MyTimeDefinition
class where you add some values to the variables inside your class.
Something like this:
您必须constructor
在MyTimeDefinition
类中创建一个类,在其中向类中的变量添加一些值。
像这样的东西:
export class MyTimeDefinition {
...
//Some other variable
constructor(){
this.mystringvariable = "my string value";
}
}
And, as you will see, when you create a new class intense by calling the constructor the variables of your class will be not empty.
而且,正如您将看到的,当您通过调用构造函数创建一个新类时,您的类的变量将不为空。