如何使用'这'嵌套对象中

How to use 'this' in nested object?

本文关键字:对象 嵌套 何使用      更新时间:2023-09-26

我正在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"

当我尝试运行方法CCD_ 1时。我还设置了构造函数:

function LayoutConstructor() {var self = this;}

并修改CCD_ 2方法:

buildSidebar: function(){
    self.general.buildBoxWrapper($(".sidebar .box-wrapper"));
}

但这似乎于事无补。

"this"是如何定义的,以及如何访问嵌套方法中的其他方法

如果不这样做。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...
        }
    }
}