2

I'm creating some methods in the LayoutConstructor object:

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

However, I get an error :

'Cannot read property 'buildBoxWrapper' of undefined'

when I try to run the method LayoutConstructor.newsroom.buildSidebar(). I also set the constructor :

function LayoutConstructor() {var self = this;}

and modify the buildSidebar method:

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

but it seems not help.

How does 'this' defined and how can I access other methods in the nested method?

Karl Bao
  • 401
  • 2
  • 4
  • 11
  • Instead of using literal notation to define the object, use function notation. That way you'll have more control on the logic. – jaibatrik Nov 26 '15 at 10:05
  • Check this out https://jsfiddle.net/u1zw7auk/ . I was able to solve the problem by passing this to buildsidebar. I am not sure if this is the best way! But i'd love to get answers from the JavaScript experts here to this question. +1 – VishwaKumar Nov 26 '15 at 10:30

1 Answers1

1

If not works this way. The self technic is a closure and it should be defined in the same function as being used. For example:

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

You can't bind this to your method the way you want. If you have bind problems, you need to change your method call:

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

It will bind the right object to this before calling your method.

By the way, you can change your class defintion to 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...
        }
    }
}
David Rissato Cruz
  • 3,347
  • 2
  • 17
  • 17