简体   繁体   English

打字稿 getter/setter 命名约定

[英]Typescript getter/setter naming convention

I come from a Java background and I defaulted to using getter/setter naming conventions in my Typescript/Angular component classes familiar to me.我来自 Java 背景,我默认在我熟悉的 Typescript/Angular 组件类中使用 getter/setter 命名约定。

getFoo()

setFoo()

However, it seems that this may not be the best practice, but rather I should use the convention但是,这似乎不是最佳实践,而是我应该使用约定

get foo()

set foo()

Questions问题

  • Is this purely cosmetic?这纯粹是化妆品吗? Any benefits?有什么好处吗? I don't understand why this would be favored since it is, to my understanding, inconsistent with the naming convention used for other methods.我不明白为什么这会受到青睐,因为据我所知,它与用于其他方法的命名约定不一致。
  • Is there a formal style guide recommending this practice?是否有正式的风格指南推荐这种做法?

We can use get , set where we need to implement some constraints when a value is accessed.我们可以使用getset在访问值时需要实现一些约束的地方。

From Typescript documentation:从打字稿文档:

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. TypeScript 支持 getter/setter 作为拦截对对象成员的访问的一种方式。 This gives you a way of having finer-grained control over how a member is accessed on each object.这使您可以更精细地控制如何在每个对象上访问成员。

Example:例子:

class StudentMark {
    isPass: boolean;
    _mark: Mark;
    set mark(value: Mark) {
        if (value.subject1 > 35 && value.subject2 > 35&& value.subject3 > 35) { 
             this.isPass = true;
        } else {
             this.isPass = false;
        }
        this._mark = value;
    }
   get mark(): Mark {
       return this._mark;
   }
}

Here, whenever we set the mark, the pass will be updated.在这里,每当我们设置标记时,通行证都会更新。 No, need to update it separately.不行,需要单独更新。 In this, type of cases get, set will be useful.在这种情况下,get、set 类型的情况会很有用。

Suffix of get and set should have same name. get 和 set 的后缀应该具有相同的名称。 And we can access it by only calling the name itself.我们可以通过仅调用名称本身来访问它。 Example, mark from above code.例如,从上面的代码中mark

For, more about get, set visit typescript documentation .有关获取、设置的更多信息,请访问 typescript 文档

type-script is superset of java-script and all of language syntax very similar of ECMAScript standard because programmer feeling better writing java-script application. type-script 是 java-script 的超集,所有语言语法都与ECMAScript标准非常相似,因为程序员感觉更好地编写 java-script 应用程序。

SET, GET property on TS & JS very similar TS 和 JS 上的 SET、GET 属性非常相似

JS JS

class JSExample {
    constructor() {
        this._val = "V";
    }
    get val() {
        return this._val;
    }
    set val($v) {
        this._val = $v;
    }
}

TS TS

class TSExample {
    _val = "V";

    get val(): string {
        return this._val;
    }
    set val($v: string) {
        this._val = $v;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM