Javascript `this` in objects-in-objects?

独自空忆成欢 提交于 2019-12-03 17:11:50

You can create a factory method:

var APP = (function(){
   var self;
   return self = {
      a : 1,
      b : function(){
          return this.a; // could be self, only differs in non-context use
      },
      c : {
          c1: function(){
               return self.a;
          }
      }
   };
})();

APP2 = APP;
APP = null;
APP2.b();  // 1
APP2.c.c1(); // 1

Two other ways of writing it:

function App() {
    var that = this;
    this.a = 1;
    this.b = function() {
        return this.a();
    };
    this.c = {
        c1: function() {
            return that.a;
        }
    }
}

function App2() {
    var app = {
        a : 1,
        b : function(){
            return this.a;
        },
        c : {
            c1: function(){
                alert(app.a);
            }
        }
    };
    return app;
}

you can use more javascriptous way to do that:

var App = function() {
    var that = this;
    this.a = 1;
    this.b = function(){
        return this.a;
    };
    this.c = {
        c1: function(){
             return that.a;
        }
    }
}

var app1 = new App();

...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!