2016-09-29 121 views
3
模块级变量和局部变量区分

考虑这个模块:如何打字稿

export module Example{ 
    let customer : any; 

    export function myExample(customer: string) { 
     // How to reference the module level customer object here? 
     // Is there a standard to make these module level variables Pascal Case to prevent this overlap? 
    } 
} 

myExample功能customer是一个字符串。我如何参考模块级别customer

如果这是一个类,我可以使用this.customerthis没有一个模块在工作,并且Example.customer也不管用,除非客户是出口......

回答

0

这里的问题TS的JS生成的版本:

define(["require", "exports"], function (require, exports) { 
    "use strict"; 
    var Example; 
    (function (Example) { 
     var customer; 
     function myExample(customer) { 
      // How to reference the module level customer object here? 
      // Is there a standard to make these module level variables Pascal Case to prevent this overlap? 
     } 
     Example.myExample = myExample; 
    })(Example = exports.Example || (exports.Example = {})); 
}); 

由于客户没有被出口,它是作为私产生。而现在,标准的Javascript变量范围规则生效,并且无法引用模块级客户。最简单的,最简单的解决方案,(恕我直言为模块级私有变量标准约定)是强调最外面的客户:

export module Example{ 
    let _customer : any; 

    export function myExample(customer: string) { 
     _customer = customer; 
    } 
} 
2

一般来说,模块无论是出口类,函数或枚举等其他元素。

export module Example如本实施例中仅示出指定Example实际上是一个命名空间中,这意味着对myexample中功能的任何引用必须由命名空间名称预先固定的,即Example.myExample()

如果客户没有出口,那么您是正确的。这是因为export module Example只是指定一个名称空间,而不是导出的变量或类。

这是很难猜测,为什么你正在使用的不是export classexport module,:

export class Example2 { 
    customer: string = 'Example2.customer'; 
    myExample(customer: string) { 
     console.log(`Example ${this.customer}`); 
     console.log(`Example ${customer}`); 
    } 
} 

这个类实际上是一个模块,由于使用export关键字。

+0

据@RyanCavanaugh http://stackoverflow.com/questions/13255158/when- (这是从2012年开始的,所以它可能已经改变了)'如果你将要有多个实例与每个实例相关联的数据,那么class就是方式去。如果你只是将逻辑连接的无状态函数组合在一起,那么模块就更合适了。“对于我的实际应用,在这个例子中,模块更有意义。 – Daryl

+0

授予。那么常客的做法是什么?这不是无国籍的功能?这意味着你正试图用一个常量值来组合一个无状态函数? – blorkfish

+0

不知道为什么它很重要。现在我把它改成了任何一个。 – Daryl