2013-11-09 3 views
2
var Higher = { 

    hello: function(){ 
    console.log('Hello from Higher'); 
    } 

    Lower: { 
    hi: function(){ 

     //how to call the 'hello()' method from the Higher namespace? 
     //without hardcoding it, as 'Higher.hello()' 

     console.log('Hi from Lower'); 
    } 
    } 
} 

하드 코딩없이 상위 네임 스페이스에서 메소드를 호출하는 방법은 무엇입니까? 다른 하위 네임 스페이스에서 상위 수준 네임 스페이스의 메서드를 호출하려는 위치의 주석을 참조하십시오.자바 스크립트 객체의 상위 네임 스페이스에 액세스하십시오.

답변

3

JavaScript에 네임 스페이스가 없습니다. 당신은 괜찮지 만 부모 개체에 액세스 할 수있는 방법이 없습니다 개체 listeral 사용하고 있습니다. 약간 더 자세하지만 클로저를 사용할 수 있습니다.

var Higher = new (function(){ 
    this.hello = function(){ 
     console.log('Hello from higher'); 
    } 

    this.Lower = new (function(higher){ 
     this.higher = higher; 

     this.hi = function(){ 
      this.higher.hello(); 

      console.log('Hi from lower'); 
     } 

     return this; 
    })(this); 

    return this; 
})(); 

Higher.hello(); 
Higher.Lower.hi(); 
관련 문제