2017-09-10 26 views
0

我在一个文件中有一个类,其中包含另一个js文件中调用的另一个静态函数。在同一个文件中的另一个帮助函数中的类中调用静态函数

module.export = class myClass{ 
    static create(){ 
    ... 
    } 
} 

// helpers 
function callCreate(){ 
    .. 
} 

我要打电话的myClass静态函数callCreate辅助函数。我怎样才能做到这一点?

class MyClass { 
 

 
    property() { 
 
    console.log('i am normal member'); 
 
    } 
 

 
    static func() { 
 
    console.log('i am static member'); 
 
    } 
 

 
    static funcThis() { 
 
    console.log('i am static member'); 
 
    console.log(this === MyClass); // true 
 
    this.func(); // will run fine as a static member of a class 
 
    this.property(); // will give error as a normal member of a class 
 
    } 
 

 
} 
 

 
(new MyClass()).property(); 
 

 
MyClass.func(); 
 

 
MyClass.funcThis();

静态成员直接由类名来访问,并且不与对象连接:

+0

该类的静态成员的访问方式如下:'Class.staticVar'。在你的情况下,它将是'myClass.create'。 – RaghavGarg

回答

1

类的静态成员等访问。另外,您只能在静态函数中使用该类的成员static

注意:@FelixKling静态函数this内将直接引用类指出。

提示:请始终使用PascalCase来命名您的班级。

+1

*“这就是你不能在静态函数中使用'this'的原因。”*这不太对。当然你可以使用'this'(每个函数都有'this''),但是它会引用'MyClass'。 –

+0

@FelixKling,我想你想说“*但它会**不**参考MyClass *”。 – RaghavGarg

+1

不,我的意思是我说的。只要把'console.log(这个=== MyClass);'在静态方法里面。 –

相关问题