typescript 静态

In Object-Oriented Programming, we write a lot of classes.

在面向对象编程中, 我们编写了许多

Classes contain properties (methods and attributes) which hold variables and operations.

类包含保存变量和操作的属性 ( 方法属性 )。

Every time we define the properties of a class, they are said to belong to either:

每当我们定义一个类的属性时,它们就被认为属于以下任何一个:

  • an instance of the class (an object created via constructor) OR

    类的实例 (通过构造函数创建的对象)或

  • the class itself (we call this a class member)

    班级本身 (我们称其为班级成员)

What do we mean by that?

那是什么意思?

How can properties belong to only the instance vs. only the class?

属性如何仅属于实例而不是

When we choose to use or omit the static keyword, it changes who the properties belong to.

当我们选择使用或省略static关键字时,它将更改属性所属的人。

Let's look at regular usage without the static keyword.

让我们看看不带static关键字的常规用法。

常规用法(属性属于实例) (Regular usage (properties belong to the instance))

Normally, when we define properties on a class, the only time they can be accessed is after we've created an instance of that class or if we use this to refer to the properties that will eventually reside on an instance of the object.

通常情况下,当我们在一个类中定义的属性,他们可以访问的唯一的一次是,我们已经创建了一个类的实例后,或者如果我们用this来指代最终将驻留在对象的实例属性。

Take this early example from White Label.

以White Label为例。

type Genre = 'rock' | 'pop' | 'electronic' | 'rap'class Vinyl {public title: string;public artist: string;public genres: Genre[];constructor (title: string, artist: string, genres: Genre[]) {this.title = title;this.artist = artist;this.genres = genres;} public printSummary (): void {console.log(`${this.title} is an album by ${this.artist}`);}
}const vinyl = new Vinyl('Goo', 'Sonic Youth', ['rock']);
console.log(vinyl.title)    // 'Goo'
console.log(vinyl.artist)   // 'Sonic Youth'
console.log(vinyl.genres)   // ['rock']
vinyl.printSummary();         // 'Goo is an album by Sonic Youth'

Each of the methods (printSummary(): void) and attributes (title, artist, genres) on the Vinyl class are said to belong to an instance of the class.

Vinyl类上的每个方法( printSummary(): void )和属性( titleartistgenres )都属于该类的实例

In the example, we were only able to access the properties title, artist and genres directly from the object after it was created.

在示例中,创建对象 ,我们只能直接从其访问titleartistgenres属性。

console.log(vinyl.title)    // This is valid!

Also note that when we use printSummary(): void, we can access title and artist using the this keyword:

还要注意,当我们使用printSummary(): void ,我们可以使用this关键字访问titleartist

class Vinyl {...public printSummary (): void {console.log(`${this.title} is an album by ${this.artist}`);}
}

That works because at this point, the resulting object / instance of Vinyl owns those properties.

之所以可行,是因为此时, Vinyl的最终对象/实例拥有这些属性。

If we check out TypeScript Playground, we can look at the compiled JavaScript for this code sample:

如果我们查看TypeScript Playground ,我们可以查看此代码示例的已编译JavaScript:

"use strict";
class Vinyl {constructor(title, artist, genres) {this.title = title;this.artist = artist;this.genres = genres;}printSummary() {console.log(`${this.title} is an album by ${this.artist}`);}
}const vinyl = new Vinyl('Goo', 'Sonic Youth', ['rock']);
console.log(vinyl.title); // 'Goo'
console.log(vinyl.artist); // 'Sonic Youth'
console.log(vinyl.genres); // ['rock']
vinyl.printSummary(); // 'Goo is an album by Sonic Youth'

The resulting JavaScript looks nearly identical.

产生JavaScript看起来几乎相同

Let's talk a bit about what happens when the properties are owned by the class.

让我们来谈一谈当属性归类所有时会发生什么。

静态属性(属性属于该类) (Static properties (properties belong to the class))

When we use the static keyword on properties we define on a class, they belong to the class itself.

当在类上定义的属性上使用static关键字时,它们属于类本身

That means that we cannot access those properties from an instance of the class.

这意味着我们无法从类的实例访问那些属性。

We can only access the properties directly by referencing the class itself.

我们只能通过引用类本身直接访问属性。

To demonstrate, let's add a counter NUM_VINYL_CREATED that increments the number of times that a Vinyl was created.

为了演示,让我们添加一个计数器NUM_VINYL_CREATED ,该计数器增加创建Vinyl的次数。

type Genre = 'rock' | 'pop' | 'electronic' | 'rap'class Vinyl {public title: string;public artist: string;public genres: Genre[];public static NUM_VINYL_CREATED: number = 0;constructor (title: string, artist: string, genres: Genre[]) {this.title = title;this.artist = artist;this.genres = genres;Vinyl.NUM_VINYL_CREATED++;        // increment number of vinyl createdconsole.log(Vinyl.NUM_VINYL_CREATED)  } public printSummary (): void { console.log(`${this.title} is an album by ${this.artist}`);}
}let goo = new Vinyl ('Goo', 'Sonic Youth', ['rock']);
// prints out 0let daydream = new Vinyl ('Daydream Nation', 'Sonic Youth', ['rock']);
// prints out 1

Because the properties can only be accessed through the class itself, we can't do:

因为只能通过类本身访问属性,所以我们不能这样做:

let goo = new Vinyl ('Goo', 'Sonic Youth', ['rock']);
goo.MAX_GENRES_PER_VINYL    // Error
goo.NUM_VINYL_CREATED       // Error

You might have heard of a term called Class Members. An attribute or a method is a class member because they can ONLY be accessed through the class itself; therefore, they're members of the class.

您可能听说过一个称为“ 班级成员 ”的术语。 属性或方法是类成员,因为只能通过类本身来访问它们。 因此,他们是班上的成员。

That's great and all, but when would you want to use static properties?

太好了,但是什么时候您想使用静态属性?

如何知道何时使用静态属性 (How to know when to use static properties)

Before you add that attribute or method, as yourself:

在自己添加该属性或方法之前,请先:

Will this property ever need to be used by another class, without having an instance of this class?

将这个属性在任何时候需要由其他类使用,而不必这个类的一个实例?

In other words, should I need to call it on an object created by this class? If yes, then continue normally.

换句话说,是否需要在此类创建的对象上调用它? 如果是,则正常继续。

If no, then you might want to make a static member.

如果否,那么您可能想成为static成员。

可能需要使用静态属性的方案 (Scenarios where it could make sense to use a static property)

  • to check a business rule or constraint from another class检查另一类的业务规则或约束
  • to implement a factory method to encapsulate the complexity required in order to create an instance of the class

    实现factory method以封装创建类实例所需的复杂性

  • to use an abstract factory in order to create a specific type of instance of the class

    使用abstract factory 来创建类的实例的特定类型

  • when the property shouldn't ever change当财产永远不应该改变

看起来很合理但实际上导致贫血的领域模型的场景: (Scenarios where it seems like it might make sense but actually leads to an anemic domain model:)

  • to perform validation logic on atttributes for that class (use Value Objects instead)

    对该类的属性执行验证逻辑(改为使用Value Objects )

To demonstrate a worthwhile scenario, let's add a static MAX_GENRES_PER_VINYL attribute to "document a constraint" that a Vinyl may only have at max 2 different types of Genres.

为了演示一个有价值的场景,让我们添加一个static MAX_GENRES_PER_VINYL属性来“记录约束”,一个Vinyl最多只能具有2种不同类型的Genres

type Genre = 'rock' | 'pop' | 'electronic' | 'rap'class Vinyl {public title: string;public artist: string;public genres: Genre[];public static MAX_GENRES_PER_VINYL: number = 2;constructor (title: string, artist: string, genres: Genre[]) {this.title = title;this.artist = artist;this.genres = genres;}public printSummary (): void { console.log(`${this.title} is an album by ${this.artist}`);}
}

And then let's add an addGenre(genre: Genre): void method to enforce this business rule.

然后,我们添加一个addGenre(genre: Genre): void方法来实施此业务规则。

type Genre = 'rock' | 'pop' | 'electronic' | 'rap'class Vinyl {public title: string;public artist: string;public genres: Genre[];public static MAX_GENRES_PER_VINYL: number = 2;constructor (title: string, artist: string, genres: Genre[]) {this.title = title;this.artist = artist;this.genres = genres;}public addGenre (genre: Genre): void {// Notice that in order to reference the value, we have go through the class// itself (Vinyl), not through an instance of the class (this).const maxLengthExceeded = this.genres.length < Vinyl.MAX_GENRES_PER_VINYL;const alreadyAdded = this.genres.filter((g) => g === genre).length !== 0;if (!maxLengthExceeded && !alreadyAdded) {this.genres.push(genre);}}public printSummary (): void { console.log(`${this.title} is an album by ${this.artist}`);}
}


Advanced TypeScript和Node.js博客 (Advanced TypeScript & Node.js blog)

If you enjoyed this article, you should check out my blog. I write about Advanced TypeScript & Node.js best practices for large-scale applications and teach developers how to write flexible, maintainable software.

如果您喜欢这篇文章,则应该查看我的博客 。 我写了针对大型应用程序的Advanced TypeScript和Node.js最佳实践,并教开发人员如何编写灵活,可维护的软件。

翻译自: https://www.freecodecamp.org/news/all-about-typescript-static-members-typescript-oop/

typescript 静态

typescript 静态_关于TypeScript静态成员的全部信息| TypeScript OOP相关推荐

  1. typescript项目_如何设置TypeScript项目

    typescript项目 by David Piepgrass 由David Piepgrass 如何设置TypeScript项目 (How to set up a TypeScript projec ...

  2. typescript 使用_如何使用TypeScript轻松修改Minecraft

    typescript 使用 by Josh Wulf 通过乔什·沃尔夫(Josh Wulf) 如何使用TypeScript轻松修改Minecraft (How to modify Minecraft ...

  3. 开发者回避使用 TypeScript 的三个借口,以及应当使用 TypeScript 的更有说服力的原因...

    本文为翻译文章 原文标题:3 Excuses Developers Give To Avoid TypeScript - and the Better Reasons They Should Use ...

  4. typescript 判断异步执行已经结束_vue进阶系列——用typescript玩转vue和vuex

    用过vue的朋友大概对vuex也不陌生,vuex的官方解释是专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. ...

  5. 静态数据成员与静态成员函数

    3-6 静态数据成员与静态成员函数 Time Limit: 1000MS Memory limit: 65536K 题目描述 通过本题目的练习可以掌握静态数据成员和静态成员函数的用法 要求设计一个点类 ...

  6. 3-6 静态数据成员与静态成员函数

    3-6 静态数据成员与静态成员函数 Time Limit: 1000MS Memory Limit: 65536KB Submit Statistic Problem Description 通过本题 ...

  7. C++学习(五) 静态数据成员和静态成员函数

    文章目录 1.静态成员: 1.1.说明 1.2.格式 2.静态成员函数 2.1.说明 2.2.格式 1.静态成员: 1.1.说明 静态成员包括静态数据和静态成员函数. (1).静态数据成员的定义与普通 ...

  8. 类的静态数据成员和静态成员函数

    一.什么是类的静态成员 静态成员变量和全局变量都存储在全局/静态区,它们都是在程序编译时创建,直到编译结束才被收回.所以全局变量和静态成员变量的功能差不多,只是创建的方式不同,类的静态成员创建在类中, ...

  9. C++类的静态数据成员和静态成员函数

    目录 公有属性 静态数据成员 静态成员函数 公有属性 一些类对象可能会具有一些相同的属性,如果用普通数据成员来描述这些相同的属性,这意味着我们需要给每个对象的这个数据成员设定相同的值,如果改变类对象相 ...

最新文章

  1. java内置_自包含的应用程序,内置Java
  2. [MySQL] 几句MySQL时间筛选SQL语句[进入查看]
  3. python 九宫重排_[蓝桥杯][历届试题]九宫重排 (Python代码)(bfs+集合)
  4. php mysql 批量insert_mysql批量插入数据方法
  5. 神奇的折纸艺术!无限翻转完全停不下来
  6. elasticsearch原理_花几分钟看一下Elasticsearch原理解析与性能调优
  7. 实例63:python
  8. java线程自带队列的使用以及线程阻塞
  9. CVPR2020 夜间目标检测挑战赛冠军方案解读
  10. 从入门到入土:[linux实践]-pam|编写基于libpam的用户认证程序|编写基于PAM认证的应用程序|详细说明|实验步骤|实验截图
  11. 异地多活设计辣么难?其实是你想多了!
  12. 阶段5 3.微服务项目【学成在线】_day03 CMS页面管理开发_17-异常处理-可预知异常处理-异常处理测试...
  13. 玩游戏计算机丢失msvcp,计算机丢失msvcp,因计算机丢失msvcp140
  14. 27服务-安全访问状态转换
  15. Excel妙用-公式结果我都要
  16. 深圳知名语音ic品牌,语音芯片方案公司,多功能语音芯片,WTV890
  17. Java中十进制数转二进制数的方法
  18. 一本《Redis 深度历险》,我能躺挣多少钱?
  19. 5G NR - RLC协议阅读笔记 - 从LTE到NR的变化
  20. PaperWork php源码,一个开源记笔记/存档的程序:Paperwork

热门文章

  1. Ubuntu 14.04中修复默认启用HDMI后没有声音的问题
  2. 查询笔记 分组与聚合 0314 1207
  3. 9206-1121-对象数组
  4. 班级的每日作业和任务目标
  5. 演练 制作爱奇异视频播放列表 0929
  6. linux-进程的理解-进程的状态与生命周期
  7. django-模板的继承
  8. linux-用户与组的概念
  9. git比较两个分支的文件的差异
  10. java基础----数据类型转化