我有一個類,如:如何定義動態創建的方法?
class Shape {
attrs : any = {};
getWidth() : number {
return this.attrs.x * 2;
}
/*some code*/
}
類具有getter和setter方法很多像getProperty()
和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, 'x');
// now we have shape.getX();
addGetter(Shape, 'y');
// now we have shape.getY();
它對javascript非常有用。但類型特徵呢?我不能做同樣的事情,我將有一個錯誤:
var shape = new Shape();
shape.getX(); // Property 'getX' does not exist on type 'Shape'.
我知道我可以創建類定義的「假」的方法,然後將其覆蓋。但看起來很難看:
class Shape {
attrs : any = {};
getWidth() : number {
return (this.attrs.x || 0) * 2;
}
// fake method
getX() : number {
return 0;
}
/*some code*/
}
// then overwrite
addGetter(Shape, 'x');
你現在對這個用例有什麼好的解決方案嗎?
我想你可以使用裝飾功能,在未來TypeScript 1.5來做到這一點...但目前在阿爾法。 – 2015-04-03 00:33:29