分配Typescript构造函数参数 [英] Assigning Typescript constructor parameters

查看:138
本文介绍了分配Typescript构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接口:

export interface IFieldValue {
    name: string;
    value: string;
}

我有实现它的类:

class Person implements IFieldValue{
    name: string;
    value: string;
    constructor (name: string, value: string) {
        this.name = name;
        this.value = value;
    }
}

在阅读这篇文章我正在考虑重构:

after reading this post I've thinking about refactoring :

class Person implements IFieldValue{
    constructor(public name: string, public value: string) {
    }
}

问题:在第一堂课中,我有一些字段,默认情况下应为 private 。在第二个示例中,我只能将它们设置为 public 。都是正确的还是我对TypeScript中的默认Access修饰符的理解?

Question : In first class I have fields which by default should be as private. In second sample I can only set them as public. Is it all correct or my understanding of default Access modifiers in TypeScript?

推荐答案


默认情况下为公共。
TypeScript文档

在以下定义中

class Person implements IFieldValue{
    name: string;
    value: string;
    constructor (name: string, value: string) {
        this.name = name;
        this.value = value;
    }
}

属性< Person> .name < Person> .value 默认情况下是公开的。

Attributes <Person>.name and <Person>.value are public by default.

他们在这里

class Person implements IFieldValue{
    constructor(public name: string, public value: string) {
        this.name = name;
        this.value = value;
    }
}

当心:这是一种错误的方法,因为 this.name this.value 将被视为未在构造函数中定义

Beware: Here is an incorrect way of doing it, since this.name and this.value will be regarded as not defined in the constructor.

class Person implements IFieldValue{
    constructor(name: string, value: string) {
        this.name = name;
        this.value = value;
    }
}

要将这些属性设为私有,您需要将其重写为

To make these attributes private you need to rewrite it as

class Person implements IFieldValue{
    private name: string;
    private value: string;
    constructor (name: string, value: string) {
        this.name = name;
        this.value = value;
    }
}

或等效地

class Person implements IFieldValue{
    constructor (private name: string, private value: string) {}
}

在我看来,这是避免重复的最可取的方法。

which in my opinion is the most preferable way that avoids redundancy.

这篇关于分配Typescript构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆