简体   繁体   English

打字稿中的Getter / Setter

[英]Getter/Setter In Typescript

I was following a tutorial on Typescript Classes and the person teaching created a class and some setter/getter methods.But when i read Typescript Documentation the approach was somewhat different. 我正在学习关于Typescript类的教程,教学人员创建了一个类和一些setter / getter方法。但是当我阅读Typescript Documentation时 ,方法有所不同。 Can someone help me understand the difference between both approaches. 有人可以帮我理解两种方法之间的区别。

Approach 1: 方法1:

class Student {
private _name: string;

constructor(name:string) {
    this._name=name;
}

getName = (): string => {
    return this._name;
}

setName = (name: string) => {
    this._name = name;
}
}

Approach 2: 方法2:

class Student {
private _name: string;

constructor(name:string) {
    this._name=name;
}

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


public set name(value: string) {
    this._name = value;
}
}

Have a look. 看一看。 In Approach 1 we write getter/setter as normal functions But in Approach 2 the keyword get/set is used. 在方法1中,我们将getter / setter写为普通函数但是在方法2中使用了关键字get / set。 Can someone help me understand the difference between both approaches. 有人可以帮我理解两种方法之间的区别。

The difference in the way you use them. 你使用它们的方式不同。 In the first case you need to explictly call the get/set methdods. 在第一种情况下,您需要明确地调用get/set方法。 In the second you can use name like an actual field on the class and the runtime will call the get/set accessors automatically. 在第二个中,您可以在类上使用类似于实际字段的name ,运行时将自动调用get/set访问器。

Consider the simple example of appending a character to the name: 考虑将一个字符附加到名称的简单示例:

Approach 1 方法1

let s = new Student();
s.setName(s.getName() + "A") // we need to explicitly call the get/ set methods

Approach 2 方法2

let s = new Student();
s.name += "A" // we can use += and the get/set accessors will get called for us

Behind the scene the get/set accessor approach (approach 2) will use Object.defineProperty 在场景后面, get/set访问器方法(方法2)将使用Object.defineProperty

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

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