Kent Liau
Kent Liau

Reputation: 935

Access higher namespace in javascript object

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');
    }
  }
}

How to call a method from a higher level namespace without hard coding? Refer to the comment where I want to call a higher level namespace's method in another lower namespace.

Upvotes: 2

Views: 130

Answers (1)

Borre Mosch
Borre Mosch

Reputation: 4564

JavaScript does not have namespaces. You are using an object listeral, which is fine but there is no way to access the parent object. You could use closures instead like this, although it is a bit more verbose:

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();

Upvotes: 3

Related Questions