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

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.

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.