在 TypeScript 中获取和设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12827266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get and set in TypeScript
提问by MuriloKunze
I'm trying to create get and set method for a property:
我正在尝试为属性创建 get 和 set 方法:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
What's the keyword to set a value?
设置值的关键字是什么?
回答by Ezward
TypeScript uses getter/setter syntax that is like ActionScript3.
TypeScript 使用类似于 ActionScript3 的 getter/setter 语法。
class foo {
private _bar: boolean = false;
get bar(): boolean {
return this._bar;
}
set bar(value: boolean) {
this._bar = value;
}
}
That will produce this JavaScript, using the ECMAScript 5 Object.defineProperty()
feature.
这将使用 ECMAScript 5Object.defineProperty()
功能生成此 JavaScript 。
var foo = (function () {
function foo() {
this._bar = false;
}
Object.defineProperty(foo.prototype, "bar", {
get: function () {
return this._bar;
},
set: function (value) {
this._bar = value;
},
enumerable: true,
configurable: true
});
return foo;
})();
So to use it,
所以要使用它,
var myFoo = new foo();
if(myFoo.bar) { // calls the getter
myFoo.bar = false; // calls the setter and passes false
}
However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use --target
flag like this;
但是,为了完全使用它,您必须确保 TypeScript 编译器针对 ECMAScript5。如果您正在运行命令行编译器,请使用这样的--target
标志;
tsc --target ES5
If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that here:
如果您使用的是 Visual Studio,则必须编辑项目文件以将该标志添加到 TypeScriptCompile 构建工具的配置中。你可以在这里看到:
As @DanFromGermany suggests below, if your are simply reading and writing a local property like foo.bar = true
, then having a setter and getter pair is overkill. You can always add them later if you need to do something, like logging, whenever the property is read or written.
正如@DanFromGermany 在下面所建议的那样,如果您只是简单地读取和写入像 那样的本地属性foo.bar = true
,那么拥有 setter 和 getter 对就太过分了。如果您需要在读取或写入属性时执行某些操作(例如记录),您可以随时添加它们。
回答by TornadoAli
Ezward has already provided a good answer, but I noticed that one of the comments asks how it is used. For people like me who stumble across this question, I thought it would be useful to have a link to the official documentation on getters and setters on the Typescript website as that explains it well, will hopefully always stay up-to-date as changes are made, and shows example usage:
Ezward 已经提供了一个很好的答案,但我注意到其中一个评论询问了它是如何使用的。对于像我这样偶然发现这个问题的人,我认为在 Typescript 网站上有一个关于 getter 和 setter 的官方文档的链接会很有用,因为它很好地解释了它,希望随着变化始终保持最新制作,并显示示例用法:
http://www.typescriptlang.org/docs/handbook/classes.html
http://www.typescriptlang.org/docs/handbook/classes.html
In particular, for those not familiar with it, note that you don't incorporate the word 'get' into a call to a getter (and similarly for setters):
特别是,对于那些不熟悉它的人,请注意不要将“get”这个词合并到对 getter 的调用中(对于 setter 也是如此):
var myBar = myFoo.getBar(); // wrong
var myBar = myFoo.get('bar'); // wrong
You should simply do this:
你应该简单地这样做:
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set) (false is correct too obviously!)
given a class like:
给定一个类,如:
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
then the 'bar' getter for the private '_bar' property will be called.
然后将调用私有 '_bar' 属性的 'bar' getter。
回答by Brian Terlson
Here's a working example that should point you in the right direction:
这是一个可以为您指明正确方向的工作示例:
class Foo {
_name;
get Name() {
return this._name;
}
set Name(val) {
this._name = val;
}
}
Getters and setters in JavaScript are just normal functions. The setter is a function that takes a parameter whose value is the value being set.
JavaScript 中的 getter 和 setter 只是普通函数。setter 是一个函数,它接受一个参数,该参数的值是被设置的值。
回答by k33g_org
You can write this
你可以写这个
class Human {
private firstName : string;
private lastName : string;
constructor (
public FirstName?:string,
public LastName?:string) {
}
get FirstName() : string {
console.log("Get FirstName : ", this.firstName);
return this.firstName;
}
set FirstName(value : string) {
console.log("Set FirstName : ", value);
this.firstName = value;
}
get LastName() : string {
console.log("Get LastName : ", this.lastName);
return this.lastName;
}
set LastName(value : string) {
console.log("Set LastName : ", value);
this.lastName = value;
}
}
回答by Willem van der Veen
TS offers getters and setters which allow object properties to have more control of how they are accessed (getter) or updated (setter) outsideof the object. Instead of directly accessing or updating the property a proxy function is called.
TS 提供了 getter 和 setter,它们允许对象属性更好地控制它们在对象外部的访问(getter)或更新(setter)方式。调用代理函数而不是直接访问或更新属性。
Example:
例子:
class Person {
constructor(name: string) {
this._name = name;
}
private _name: string;
get name() {
return this._name;
}
// first checks the length of the name and then updates the name.
set name(name: string) {
if (name.length > 10) {
throw new Error("Name has a max length of 10");
}
this._name = name;
}
doStuff () {
this._name = 'foofooooooofoooo';
}
}
const person = new Person('Willem');
// doesn't throw error, setter function not called within the object method when this._name is changed
person.doStuff();
// throws error because setter is called and name is longer than 10 characters
person.name = 'barbarbarbarbarbar';
回答by Angel Angel
It is very similar to creating common methods, simply put the keyword reserved get
or set
at the beginning.
它与创建常用方法非常相似,只需将关键字保留get
或set
放在开头即可。
class Name{
private _name: string;
getMethod(): string{
return this._name;
}
setMethod(value: string){
this._name = value
}
get getMethod1(): string{
return this._name;
}
set setMethod1(value: string){
this._name = value
}
}
class HelloWorld {
public static main(){
let test = new Name();
test.setMethod('test.getMethod() --- need ()');
console.log(test.getMethod());
test.setMethod1 = 'test.getMethod1 --- no need (), and used = for set ';
console.log(test.getMethod1);
}
}
HelloWorld.main();
In this case you can skip return type in get getMethod1() {
在这种情况下,您可以跳过返回类型 get getMethod1() {
get getMethod1() {
return this._name;
}
回答by dasfdsa
I think I probably get why is it so confusing. In your example, we wanted getters and setters for _name
. But we achieve that by creating getters and setters for an unrelated class variable Name
.
我想我可能明白为什么它如此令人困惑。在您的示例中,我们想要 .getter 和 setter 方法_name
。但是我们通过为不相关的类变量创建 getter 和 setter 来实现这一点Name
。
Consider this:
考虑一下:
class Car{
private tiresCount = 4;
get yourCarTiresCount(){
return this.tiresCount ;
}
set yourCarTiresCount(count) {
alert('You shouldn't change car tire count')
}
}
Above code does following:
上面的代码执行以下操作:
get
andset
create getter and setter foryourCarTiresCount
(not fortiresCount
).
get
并set
为yourCarTiresCount
(不是 fortiresCount
)创建 getter 和 setter 。
The getter is :
吸气剂是:
function() {
return this.tiresCount ;
}
and the setter is :
而二传手是:
function(count) {
alert('You shouldn't change car tire count');
}
Meaning, every time we do new Car().yourCarTiresCount
, getter runs. And for every new Car().yourCarTiresCount('7')
setter runs.
意思是,每次我们这样做时new Car().yourCarTiresCount
,getter 都会运行。并且对于每个new Car().yourCarTiresCount('7')
二传手运行。
- Indirectlycreate getter, but not the setter, for private
tireCount
.
- 为 private间接创建 getter,而不是 setter
tireCount
。
回答by cjbarth
If you are working with TypeScript modules and are trying to add a getter that is exported, you can do something like this:
如果您正在使用 TypeScript 模块并尝试添加导出的 getter,您可以执行以下操作:
// dataStore.ts
export const myData: string = undefined; // just for typing support
let _myData: string; // for memoizing the getter results
Object.defineProperty(this, "myData", {
get: (): string => {
if (_myData === undefined) {
_myData = "my data"; // pretend this took a long time
}
return _myData;
},
});
Then, in another file you have:
然后,在另一个文件中,您有:
import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"