在 TypeScript 中获取和设置 [英] get and set in TypeScript

查看:36
本文介绍了在 TypeScript 中获取和设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为属性创建 get 和 set 方法:

I'm trying to create get and set method for a property:

private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}

设置值的关键字是什么?

What's the keyword to set a value?

推荐答案

TypeScript 使用类似于 ECMAScript4/ActionScript3 的 getter/setter 语法.

TypeScript uses getter/setter syntax that is like ECMAScript4/ActionScript3.

class foo {
    private _bar: boolean = false;
    get bar(): boolean {
        return this._bar;
    }
    set bar(value: boolean) {
        this._bar = value;
    }
}

这将使用 ECMAScript 5 Object.defineProperty() 功能生成此 JavaScript.

That will produce this JavaScript, using the ECMAScript 5 Object.defineProperty() feature.

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

所以要使用它,

var myFoo = new foo();
if(myFoo.bar) {         // calls the getter
    myFoo.bar = false;  // calls the setter and passes false
}

但是,为了完全使用它,您必须确保 TypeScript 编译器针对 ECMAScript5.如果您正在运行命令行编译器,请像这样使用 --target 标志;

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;

tsc --target ES5

如果您使用的是 Visual Studio,则必须编辑您的项目文件以将标志添加到 TypeScriptCompile 构建工具的配置中.您可以在此处看到:

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:

正如@DanFromGermany 在下面建议的那样,如果您只是读取和写入像 foo.bar = true 这样的本地属性,那么拥有一个 setter 和 getter 对就有点过分了.如果您需要在读取或写入属性时执行某些操作(例如记录日志),您可以随时添加它们.

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.

Getter 可用于实现只读属性.这是一个示例,它也展示了 getter 如何与只读和可选类型交互.

Getters can be used to implement readonly properties. Here is an example that also shows how getters interact with readonly and optional types.

//
// type with optional readonly property.
// baz?:string is the same as baz:string|undefined
//
type Foo = {
    readonly bar: string;
    readonly baz?: string;
}
const foo:Foo = {bar: "bar"}
console.log(foo.bar) // prints 'bar'
console.log(foo.baz) // prints undefined

//
// interface with optional readonly property
//
interface iFoo {
    readonly bar: string;
    readonly baz?: string;
}

const ifoo:iFoo = {bar: "bar"}
console.log(ifoo.bar)  // prints 'bar'
console.log(ifoo.baz)  // prints undefined


//
// class implements bar as a getter, 
// but leaves off baz.
//
class iBarClass implements iFoo {

    get bar() { return "bar" }
}
const iBarInstance = new iBarClass()
console.log(iBarInstance.bar)  // prints 'bar'
// accessing bas gives warning that bas does not exist 
// on iBarClass but returns undefined
console.log(iBarInstance.bas) // prints 'undefined'
// note that you could define baz as a getter
// and just return undefined to remove the warning.


//
// class implements optional readonly property as a getter
//
class iBazClass extends iBarClass {
    private readonly _baz?: string

    constructor(baz?:string) {
        super()
        this._baz = baz
    }

    get baz() { return this._baz; }
}

const iBazInstance = new iBazClass("baz")
console.log(iBazInstance.bar)  // prints bar
console.log(iBazInstance.baz)  // prints baz

这篇关于在 TypeScript 中获取和设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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