在TypeScript中获取和设置

本文翻译自:get and set in TypeScript

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? 设置值的关键字是什么?


#1楼

参考:https://stackoom.com/question/roxO/在TypeScript中获取和设置


#2楼

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. JavaScript中的getter和setter只是普通函数。 The setter is a function that takes a parameter whose value is the value being set. setter是一个函数,它接受一个参数,其值是设置的值。


#3楼

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;
    } 

}

#4楼

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 5 Object.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. 但是,为了完全使用它,您必须确保TypeScript编译器以ECMAScript5为目标。 If you are running the command line compiler, use --target flag like this; 如果您正在运行命令行编译器,请使用--target标志,如下所示;

tsc --target ES5 tsc - 目标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. 如果使用的是Visual Studio,则必须编辑项目文件,以将标志添加到TypeScriptCompile构建工具的配置中。 You can see that here : 你可以在这里看到:

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. 正如@DanFromGermany在下面建议的那样,如果你只是阅读和写一个像foo.bar = true这样的本地属性,那么拥有一个setter和getter对就是矫枉过正。 You can always add them later if you need to do something, like logging, whenever the property is read or written. 如果您需要在读取或写入属性时执行某些操作(如日志记录),则可以随后添加它们。


#5楼

Ezward has already provided a good answer, but I noticed that one of the comments asks how it is used. Ezward已经提供了一个很好的答案,但我注意到其中一条评论询问它是如何使用的。 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: 对于像我这样偶然发现这个问题的人,我认为在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。


#6楼

It is very similar to creating common methods, simply put the keyword reserved get or set at the beginning. 它与创建常用方法非常相似,只需将关键字reserved getset为开头即可。

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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值