小编lav*_*ton的帖子

如何定义动态创建的方法?

我有一个类:

class Shape {
   attrs : any = {};
   getWidth() : number {
       return this.attrs.x * 2;
   }
  /*some code*/
}
Run Code Online (Sandbox Code Playgroud)

该类有很多 getter 和 setter 方法,例如getProperty()and setProperty()。几乎所有这些都以相同的方式工作,但具有不同的属性。为了避免类定义中的大量代码重复,我动态添加了这样的方法:

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function addGetter(constructor, attr, defaultValue) : void {
    var method = 'get' + capitalize(attr);
    constructor.prototype[method] = function() {
        var val = this.attrs[attr];
        return val === undefined ? defaultValue : val;
    };
}

// then add a lot of getters in fast way
addGetter(Shape, …
Run Code Online (Sandbox Code Playgroud)

typescript

1
推荐指数
1
解决办法
2538
查看次数

标签 统计

typescript ×1