2015-04-02 43 views
1

我有一個類,如:如何定義動態創建的方法?

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'); 

你現在對這個用例有什麼好的解決方案嗎?

+0

我想你可以使用裝飾功能,在未來TypeScript 1.5來做到這一點...但目前在阿爾法。 – 2015-04-03 00:33:29

回答

2

function addGetter(constructor, attr, defaultValue) : void

這實際上是一個mixin。目前在TypeScript中沒有關於mixin的好故事。有如何鍵入它的文檔:https://github.com/Microsoft/TypeScript/wiki/Mixins

您基本上聲明這些成員存在,但不提供實施。

class Shape { 
    attrs : any = {}; 

    getWidth() : number { 
     return (this.attrs.x || 0) * 2; 
    } 
    // declared only 
    getX:()=> number; 

    /*some code*/ 
} 

// then define 
addGetter(Shape, 'x'); 

混入都在路線圖2.0:http://github.com/Microsoft/TypeScript/wiki/Roadmap#20你也可以從這裏開始討論:http://github.com/Microsoft/TypeScript/issues這將是巨大的,如果你能拿出一個提案

+0

好。看起來這是最好的方法。 – lavrton 2015-04-03 14:25:15