2017-09-10 1 views
0

다른 js 파일에서 호출되는 다른 정적 함수가 들어있는 파일에 클래스가 있습니다.동일한 파일의 다른 도우미 함수에서 클래스의 정적 함수를 호출하십시오.

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

// helpers 
function callCreate(){ 
    .. 
} 

나는 callCreate 도우미 함수에 myClass의 정적 함수를 호출합니다. 어떻게해야합니까?

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 멤버 만 사용할 수 있습니다.

주의 사항 :으로 클래스를 직접 참조 할 정적 기능 this 내부을 @FelixKling 에 의해 지적했다.

팁 : 클래스 이름을 지정하는 데 항상 PascalCase을 사용하십시오.

+1

* "정적 함수 안에서 'this'를 사용할 수없는 이유입니다."* 맞지 않습니다. 물론'this' (모든 함수에'this'가 있습니다)를 사용할 수는 있지만'MyClass'를 참조 할 것입니다. –

+0

@FelixKling, 나는 당신이 "*하지만 ** ** MyClass *를 언급하지 않을 것"이라고 말하고 싶다고 생각합니다. – RaghavGarg

+1

아니, 나는 내가 말한 것을 의미했다. static 메소드 안에'console.log (this === MyClass);'를 넣으면된다. –

관련 문제