Search code examples
javascripttidesdk

Calling a function within a Nested Object


I have an object, nested within a parent object. The inner object has 2 functions and one needs to call the other. I assumed I could call this.theFunction(), but that doesn't seem to be the case.

var views = {
  settings: {
    init: function() {
      this.doSomething(withThing);
    },

    doSomething: function(with) {
      // NEVER GETS CALLED
    }
  }
};

In this case, this seems to reference a DOMWindow rather than the views.settings object as I was expecting. What am I missing?

UPDATE

The views.settings.init() function is called as a callback. An external process calls template.init(view, views.settings.init);. The latter argument is a callback. Within template.init(), the callback is simply called as callback(). For clarity (hopefully), here's a snippet of how we get to views.settings.init:

template.init(view, views.settings.init);
var template: {
  init: function() {
    callback();
  }
}

What would cause the context to get lost and what can I do to get it back so that this references the views.settings object?


Solution

  • Try doing this:

    var views = {
       settings: {
        init: function() {
            var withThing = 'withThing';
            this.doSomething(withThing);
        },
    
        doSomething: function(withThing) {
          // NEVER GETS CALLED
            alert(withThing)
        }
      }
    };
    
    views.settings.init();
    

    Here's a jsfiddle