angular - TypeScript 中类属性的命名约定

标签 angular typescript parameters naming-conventions

根据offical style guide你应该

Avoid prefixing private properties and methods with an underscore.

因为我有 Java 背景,所以我通常只使用 this 关键字:

export default class Device {
    private id: string;

    constructor(id: string) {
        this.id = id;
    }

    public get id(): string { // [ts] Duplicate identifier 'id'.
        return this.id;
    }

    public set id(value: string) { // [ts] Duplicate identifier 'id'.
        this.id = value;
    }
}

但是 TypeScript 编译器会提示:[ts] 重复的标识符“id”。

TypeScript 构造函数中的参数命名是否有约定或最佳实践?

使用 TypeScript 的 getset 属性会产生错误。

有没有一种方法既可以遵循样式指南又可以使用 TypeScript 的 get/set 属性?

最佳答案

回答

如果您想使用getset 访问器,您必须在私有(private)属性前加上下划线。在所有其他情况下不要使用它。我会说在访问器中使用下划线是一种特殊情况,虽然它没有明确写在 Coding guidelines 中。 ,这并不意味着它是错误的。他们在 official documentation 中使用它.

下划线的原因

首先,我想强调一下 fieldproperty 之间的区别。在标准的高级 OOP 语言(如 Java 或 C#)中,字段是一个私有(private)成员,不应对其他类可见。如果您想以封装的方式公开它,您应该创建一个属性。

Java 中,您可以这样做(称为 Bean 属性):

private int id;

public int getId() {
    return this.id;
}

public setId(int value) {
    this.id = value;
}

然后您可以通过调用这些方法来访问该属性:

int i = device.getId();
device.setId(i);

//increment id by 1
device.setId(device.getId() + 1);

另一方面,C# 的设计使其更易于使用属性:

private int id;

public int Id {
    get {
        return this.id;
    }
    set {
        this.id = value;
    }
}

(值始终是分配的值。)

您可以直接为这些属性赋值或获取属性值。

int i = device.Id;
device.Id = i;

//increment id by 1
device.Id++;

在纯 JavaScript 中,没有真正的字段,因为类成员始终是公共(public)的;我们简单地称它们为属性。

TypeScript 中,您可以定义“真正的”类 C# 属性(带有封装)。您使用 Accessors为此。

private _id: number;

public get id(): number {
    return this._id;
}

public set id(value: number) {
    this._id = value;
}

用法:

let i: number = device.id;
device.id = i;

//increment id by 1
device.id++;

必须在这里使用下划线有两个原因:

  1. 在 JavaScript 中,所有类成员都是公共(public)的。因此,通过在私有(private)属性前加上下划线,我们表示该属性(字段)是私有(private)的,只能由其公共(public)属性访问。
  2. 如果您用相同的名称命名私有(private)属性和公共(public)属性,JavaScript 解释器将不知道是访问私有(private)属性还是公共(public)属性。因此,您会收到您所写的错误:[ts] 重复标识符“id”。

关于angular - TypeScript 中类属性的命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40587873/

相关文章:

javascript - 在 Angular2 指令中注入(inject) Angular1 服务

javascript - 如何读取 Cypress 的数据值?

angular - 您如何在 ngOnInit 生命周期中测试可观察对象?

Angular 2 & d3 : How to call this when function this exists

javascript - 如何在 TypeScript 中表达幂等(自展平)类型?

php - jQuery 函数将我的参数转换为 int

javascript - 如何从 for 循环返回解析 Promise Like 对象

javascript - typescript + lodash - 找不到模块

java - 在Java中显式引用方法参数

c++ - 为什么 C++ 允许未命名的函数参数?