如何在嵌套对象中使用'this'?

时间:2015-11-26 09:59:48

标签: javascript

我正在 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'以及如何在嵌套方法中访问其他方法?

1 个答案:

答案 0 :(得分:1)

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

function myFunc() {
     var self = this;
     anotherFuncWithCallback( function() { self.myValue = this.valueFromOtherContext; });
}

您无法以您希望的方式将this绑定到您的方法。如果遇到绑定问题,则需要更改方法调用:

myObject.myMethod.bind(myObject)("parameters");

在调用方法之前,它会将正确的对象绑定到this

顺便说一句,您可以将课程定义更改为:

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...
        }
    }
}