Javascript 如何使用';这';在嵌套对象中?

Javascript 如何使用';这';在嵌套对象中?,javascript,Javascript,我正在LayoutConstructor对象中创建一些方法: function LayoutConstructor() {}; LayoutConstructor = { buildNewsroom: function() { this.newsroom.buildSidebar(); }, newsroom: { buildSidebar: function() { //some code...

我正在LayoutConstructor对象中创建一些方法:

function LayoutConstructor() {};
LayoutConstructor = {
    buildNewsroom: function() {
        this.newsroom.buildSidebar();
    },
    newsroom: {

        buildSidebar: function() {
            //some code...
            //get the error: Cannot read property 'buildBoxWrapper' of undefined
            this.general.buildBoxWrapper($(".sidebar .box-wrapper"));
        }
    },
    general: {

        // Build the box-wrapper
        buildBoxWrapper: function(boxWrapper) {
            //some code...
        }
    }
}
但是,我得到一个错误:

'无法读取未定义的'buildBoxWrapper'属性'

当我尝试运行方法
LayoutConstructor.newsroom.buildSidebar()
时。 我还设置了构造函数:

function LayoutConstructor() {var self = this;}
并修改
buildSidebar
方法:

buildSidebar: function(){
    self.general.buildBoxWrapper($(".sidebar .box-wrapper"));
}
但这似乎没有帮助


如何定义“this”以及如何访问嵌套方法中的其他方法?

如果不是这样工作的话。
self
技术是一个闭包,应该在使用的相同功能中定义它。例如:

function myFunc() {
     var self = this;
     anotherFuncWithCallback( function() { self.myValue = this.valueFromOtherContext; });
}
您不能以您想要的方式将
绑定到您的方法。如果存在绑定问题,则需要更改方法调用:

myObject.myMethod.bind(myObject)("parameters");
在调用方法之前,它会将正确的对象绑定到此

顺便说一下,您可以将类定义更改为:

var LayoutConstructor = function() {

  var self = this;

  this.newsroom = {
        buildSidebar: function() {
            //some code...
            //get the error: Cannot read property 'buildBoxWrapper' of undefined
            self.general.buildBoxWrapper($(".sidebar .box-wrapper"));
        }
    };

  this.buildNewsroom = function() {
        this.newsroom.buildSidebar();
  };



  this.general = {

        // Build the box-wrapper
        buildBoxWrapper: function(boxWrapper) {
            //some code...
        }
    }
}

不要使用文字符号来定义对象,而是使用函数符号。这样你就可以更好地控制逻辑。看看这个。我可以通过将此消息传递到buildsidebar来解决这个问题。我不确定这是不是最好的办法!但是我很想从这里的JavaScript专家那里得到这个问题的答案+1.