访问typescript属性的getter和setter

时间:2015-03-06 16:47:15

标签: properties typescript

我有一个关于typescript属性的问题:是否可以获取typescript属性的setter和getter或者声明一个函数参数属于X类型的属性?

原因是获得某种变量的“引用”,这在普通JS中是不可能的,无需编写getter / setter包装器或通过父对象本身访问变量(obj [“varname”])。

例如(有一些工作代码和其他推测部分):

//A sample class with a property
class DataClass<T> {
    private T val;

    public get value(): T {
        return this.val;
    }

    public set value(value: T) {
        this.val = value;
    }
}

//Different ways of modifing a member "by reference"
class ModifyRef {
    public static void DoSomethingByGetterAndSetter(getter: () => string, setter: (val: string) => void) {
        var oldValue = getter();
        setter("new value by DoSomethingByGetterAndSetter");
    }

    public static void DoSomethingByObject(obj: Object, name: string) {
        var oldValue = obj[name];
        obj[name] = "new value by DoSomethingByObject";
    }

    //Is something like this possible?
    public static void DoSomethingByProperty(somePropery: property<string>) {
        var oldVlaue = someProperty;
        someProperty = "new value by DoSomethingByProperty";
    }
}

var inst = new DataClass<string>();

//Calling the DoSomethingByProperty if possible
ModifyRef.DoSomethingByProperty(inst.value);

//Or if not is something like this possible
ModifyRef.DoSomethingByGetterAndSetter(inst.value.get, inst.value.set);

2 个答案:

答案 0 :(得分:1)

最简单的方法是提供方法,而不是属性:

//A sample class with a property
class DataClass<T> {
    private val: T;

    public getValue(): T {
        return this.val;
    }

    public setValue(value: T) {
        this.val = value;
    }
}

class ModifyRef {
    public static DoSomethingByGetterAndSetter(getter: () => string, setter: (val: string) => void) {
        var oldValue = getter();
        setter("new value by DoSomethingByGetterAndSetter");
    }
}

var inst = new DataClass<string>();

//Or if not is something like this possible
ModifyRef.DoSomethingByGetterAndSetter(inst.getValue, inst.setValue);

答案 1 :(得分:0)

我很久以前发现,带有属性的语言不包含对属性进行引用的便捷方式,have daydreamed about having this feature in C#非常令人惊讶。它也应该处理局部变量。

这种一流或具体化属性的流行模式是一个可以通过两种方式调用的单一函数:

  1. 无参数:返回当前值。
  2. 一个参数:设置值,返回undefined
  3. 或者在TypeScript术语中:

    interface Property<T> {
        (): T;
        (newVal: T): void;
    }
    

    jQuery对象的方法通常像这样工作。这种模式在纯数据建模中的一个例子是Knockout,其中这些属性也支持变更订阅,并且有一个相当优雅的模式来定义计算属性,这些属性会在它们的依赖变化时自动重新计算。

相关问题