在javascript对象中访问更高的命名空间

时间:2013-11-09 15:48:25

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

如何在没有硬编码的情况下从更高级别的命名空间调用方法?请参阅我要在另一个较低命名空间中调用更高级别命名空间方法的注释。

1 个答案:

答案 0 :(得分:3)

JavaScript没有名称空间。您正在使用对象侦听,这很好,但无法访问父对象。你可以像这样使用闭包,虽然它有点冗长:

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