javascript - Typescript 是否在类构造函数中设置接口属性?
问题描述
在有关接口的 Typescript 文档中,在“类类型”下,给出了以下示例:
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
constructor(h: number, m: number) { }
}
“class Clock...”下面以“currentTime:...”开头的行似乎暗示如果我这样做var something = new Clock()
,我的something
变量将具有currentTime
可访问的属性,即something.currentTime
.
这让我感到困惑,因为MDN 文档中关于 Javascript Classes的以下行:
实例属性必须在类方法中定义
他们给出的例子:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
这意味着以下代码将无效:
class Rectangle {
height: 23,
width: 45,
constructor(height, width) {
}
}
我的困惑:Typescript 文档中的示例代码没有在构造函数中分配 currentTime。他们的示例中是否缺少该步骤,或者他们的语法是否暗示“顺便说一句,直接在类上定义的属性在构造函数中被神奇地赋予了值?” 如果是这种情况,如果您自己“手动”在构造函数中设置给定值会发生什么?
解决方案
class Clock implements ClockInterface {
currentTime: Date = new Date();
constructor(h: number, m: number) { }
}
运行构造函数,然后连接分配默认值的任何属性,以便在调用构造函数后分配 currentTime。
这允许语法像
class MyClass {
myProperty = this.myService.serviceProperty;
constructor(private myService: Myservice) {}
}
将构造函数参数标记为私有、受保护或公共自动将它们分配为类的属性,您不需要这样做
this.property = paramater
在构造函数中。TypeScript 语法与 JavaScript 不同,但一旦你习惯了它就很棒。
推荐阅读
- javascript - Message: count(): Parameter must be an array or an object that implements Countable in codeigniter model
- python - 将 CSV 文件加载到 NumPy memmap 数组使用太多内存
- pytorch - 函数 nn.LSTM 在 batches/seq_len 中的行为如何?
- php - 尝试组合两个数组不起作用
- mysql - 如何找出消息是否包含MYSQL中列中的关键字
- javascript - 音频文件无法在 reactjs 中播放
- c - C 套接字 - recv() 和 recvfrom() - 使用指定的模数而不是顺序写入内存?
- c++ - Build mysql-connector-c++-8.0.17-src with MinGW on Windows
- spring-boot - 如何将响应发送回网关接口?
- javascript - NuCaptcha 不渲染