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

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

4

1 回答 1

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();
于 2013-11-09T15:55:39.023 回答