2013-06-26 40 views
1

让我们说我想扩展一个模块。同时我不想重写它的属性。在JavaScript中,我会做:在TypeScript中扩展不覆盖模块

var root = this; // window 
(function(exports) { 
    if ('widget' in exports) return; 

    function widget() { 
     // 
    } 

    exports.widget = widget; 

})(root.library || (root.library = {})); 

这似乎使用module是打字稿提供相同。但使用它通过以下方式将不加区别地替代了以前的library定义的任何widget属性:

module library { 
    export function widget() { 
     // 
    } 
} 

现在我可以使用前者,但随后打字稿抱怨嵌套一个class定义,如果我创建一个函数内部。如果我把这个定义放在函数之外,那么它就会被导出(比如window),这是我想要避免的。

任何想法?

+0

为此避免基于类的继承的动机是什么? – Fenton

+0

@SteveFenton你能提供一个例子吗?我的答案在底部做我正在寻找的东西。 – Radek

回答

0

OK 用户错误,下面的工作正常,我得到的唯一的警告是外函数定义回报,但也就是不是TypeScript错误:

module library { 
    if (library.widget) { 
     return; 
    } 

    class Internal { 

    } 

    export function widget() { 

    } 
} 
0

你可以用瓦尔做到这一点:

module library { 
    export var widget = function() { 
     // 
    } 
} 

module library{ 
    if(library.widget){ 
     return; 
    } 
    else{ 
     library.widget = function(){    
     } 
    } 
} 

Try it.

0

根据要求,她e是一个简单的例子,它使用基于类的继承来提供一个小部件,然后提供一个小部件的专用版本。这允许您重新使用原始小部件中的代码,并在不更改调用代码的情况下替换不同类型的小部件。

module Example { 
    export class WidgetBase { 
     doWidgetThings() { 
      return 'Base widget things'; 
     } 

     doOtherThings() { 
      return 'Base other things'; 
     } 
    } 

    export class WidgetSpecialisation extends WidgetBase { 
     doWidgetThings() { 
      return 'Special widget things'; 
     } 

     doOtherThings() { 
      return super.doOtherThings(); 
     } 
    } 
} 

var widget = new Example.WidgetSpecialisation(); 
alert(widget.doWidgetThings() + ' ' + widget.doOtherThings()); 
+0

对不起史蒂夫,我没有很好地描述我的问题。这个想法是,我将我的小部件嵌入到一个我一无所知的页面中。所以我只是想为模块添加属性,但如果该模块已经具有这些属性,则返回。 – Radek