从JavaScript到TypeScript,Pt。 IIB:使用类,接口和混合器进行设计

Class-based design has become such an instinct that many developers can't imagine any alternative.

基于类的设计已经成为一种本能,许多开发人员无法想象任何替代方案。

Fortunately for that lot, ES6 adds a class keyword to simplify the syntactical cacophany of working with JavaScript's native prototypes. TypeScript goes further, adding support for access modifiers; interfaces; enums; and a smörgasbård of other classical object-oriented goodies.

幸运的是,ES6添加了一个class关键字来简化使用JavaScript的本机原型的句法模糊性。 TypeScript更进一步,增加了对访问修饰符的支持; 接口; 枚举 以及其他一些经典的面向对象的东西。

Of course, JavaScript doesn't have native classes. Nor does it have native interfaces. Nor does it have native access modifiers. TypeScript does a good job of emulating them, but the illusion can't be total. Keep that in mind, as it's possible to slip past the compile-time checks if you're clever enough.

当然,JavaScript没有本机类。 它也没有本机接口。 它也没有本机访问修饰符。 TypeScript在模拟它们方面做得很好,但是错觉并不能完全解决。 请记住这一点,因为如果您足够聪明,就有可能跳过编译时检查。

After reading this article, you'll be able to:

阅读本文之后,您将能够:

  • Write and design robust classes and interfaces;

    编写和设计健壮的类和接口;
  • Decide whether classes or interfaces are more appropriate for your use case; and

    确定类或接口是否更适合您的用例; 和
  • Article the major principles of object-oriented programming and design.

    文章介绍了面向对象编程和设计的主要原理。

All the code samples for this article are hosted at my GitHub. Clone it down, and run:

本文的所有代码示例都托管在我的GitHub上 。 克隆下来,然后运行:

git checkout Part-2B-OOP_Design_Principle

If you're on Windows, you should be able to run tsc --target ES5. You'll get a frightening bundle of errors, but you can safely ignore them.

如果您使用的是Windows,则应该能够运行tsc --target ES5 。 您会收到一系列令人恐惧的错误,但可以放心地忽略它们。

If you're on Linux or Mac, you'll still run tsc, but you can pipe the errors to nowhere:

如果您使用的是Linux或Mac,则仍将运行tsc ,但可以将错误传递到任何地方:

# Compile all TS files, and silence irrelevant errors.
tsc --target ES5 > /dev/null 2>&1

Either way, you should end up with a folder called built with the transpiled JavaScript.

无论哪种方式,您都应该最终获得一个由已编译JavaScript built的文件夹。

Catch Up: Read From JavaScript to TypeScript Parts I and IIA

追赶 :从JavaScript读到TypeScript Part I和IIA

类:背景和设计注意事项 ( Classes: Background & Design Considerations )

At the risk of sounding like a broken record: JavaScript does not have classes. It has a class keyword. These are very different things.

听起来有破纪录的危险: JavaScript没有类它有一个class关键字 。 这些是完全不同的东西。

JavaScript uses prototype-based delegation to achieve what Java and C++ accomplish with classes. Even though we might be more comfortable with classical OOP, and even though we might be able to emulate it with prototypes, it will only ever be an emulation.

JavaScript使用基于原型的委托来实现Java和C ++使用类完成的工作。 即使我们对经典的OOP可能更满意,即使我们可以用原型对其进行仿真但它永远只是一种仿真

Under the hood, it's prototypes all the way down.

在引擎盖下,它一直是原型。

That's why it's crucial to understand how JavaScript's classes and prototypes work under the hood. You don't have to like them, but life will be easier if you're familiar with them.

这就是为什么了解JavaScript的类和原型如何在后台运行至关重要。 您不必喜欢它们,但是如果您熟悉它们,生活会更轻松。

抽象和代码重用 (Abstraction & Code Reuse)

DRY code is not necessarily good code, but good code is pretty much always DRY.

DRY代码 不一定是好的代码,但是好的代码几乎总是DRY。

Avoid duplicate code is such a common admonition in modern development that it's hard to write the same code twice without feeling . . . Dirty. And for good reason: If you write your code in one place, and reuse it elsewhere, you'll only have one place to worry about when you debug, maintain, or extend it.

避免重复代码是现代开发中的常见建议,很难两次编写相同的代码。 。 。 脏。 并有充分的理由:如果您将代码编写在一个地方,然后在其他地方重用,则在调试,维护或扩展代码时,只需要担心一个地方。

The basic motivation for classes and objects derives from a similar principle

类和对象的基本动机源自相似的原理

Objects provide a way to associate a data of a certain shape with behavior.

对象提供了一种将特定形状数据行为相关联的方法

Objects provide a way to associate a data of certain shapes with behaviors -- that is, things you'll often want to do with that data. Classes provide a way to desribe those shapes and behaviors in the abstract, making it easy for us to create arbitrariy many similar objects throughout the lifetime of our program.

对象提供了一种将某些形状数据行为相关联的方法 -也就是说,您经常需要对该数据进行处理。 提供了一种抽象描述这些形状和行为的方法,使我们可以在程序的整个生命周期内轻松创建任意相似的对象。

Put another way, a class is like a blueprint: It describes how to build a house. The house is the object itself. Building the house according to the blueprint is analogous to instantiating an object from the class. If we want to change the way the house is built, everywhere it's built, all we have to do is change the blueprint -- not the houses.

换句话说,一个类就像一个蓝图:它描述了如何盖房子。 房子是物体本身。 根据蓝图建造房屋类似于从类中实例化对象。 如果我们想改变房屋的建造方式, 无论房屋到处都是 ,我们要做的就是更改蓝图- 而不是房屋。

We create classes and objects that reflect the structural components of the problems we're solving. This allows us to reason about our programs at a high level of abstraction, which is one of the fundamental aspects of OOP.

我们创建的类和对象反映了我们正在解决的问题的结构性组成部分。 这使我们能够以高度抽象的方式对程序进行推理,这是OOP的基本方面之一。

// user.ts
"use strict";

// Blueprint :: This doesn't create users. It just describes them.
class User {
    

    constructor (private _name : string,
                 private _email : string) {
    }

    get name () : string  {
     return this._name; }

    get email () : string {
     return this._email; }

    speak () : void {
     console.log(`I am ${
      this.name}!`);

}

// Instantiation :: Create an actual thing that acts as the class describes.
const peleke = new User('Peleke', 'resil.design@gmail.com');
console.log(peleke.name);

An object expresses its behavior through the functions attached to it, called methods, and it holds its data, or state, in instance variables.

对象通过附加到它的函数(称为方法)来表达其行为 ,并将其数据状态保存在实例变量中

In JavaScript, instantiated objects get their own instance variables, but delegate method calls to the class's prototype object. In other words, each object gets its own data, but shares methods with other instances of the class.

在JavaScript中,实例化的对象获得其自己的实例变量,但是将委托方法调用委托给该类的原型对象。 换句话说,每个对象都有自己的数据,但与该类的其他实例共享方法。

That means two things:

这意味着两件事:

  1. If you change methods on the class prototype, all of your instances will behave differently, even if you created them before making the change; and

    如果您在类原型上更改方法,则即使您在进行更改之前创建了它们,所有实例的行为也会有所不同。 和
  2. If you add methods to the class's prototype, all of your instances will be able to call them, even if you created your objects before a
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值