0

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?

Rob Wilkerson
  • 40,476
  • 42
  • 137
  • 192
  • 2
    Whatever's calling your "init" function is doing so in such a way as to lose the context (the `this` value). The default value for `this` is the global context (unless you're in "strict" mode). – Pointy Jan 29 '14 at 14:59
  • `views.settings.doSomething()`? – BenM Jan 29 '14 at 15:01
  • 1
    also `with` is a reserved keyword, see http://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement – Biketire Jan 29 '14 at 15:02
  • Question updated to try to offer some clarity. I wasn't actually using `with` as a variable. It was a poor choice in my example. :-) – Rob Wilkerson Jan 29 '14 at 15:13

1 Answers1

1

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

James
  • 2,195
  • 1
  • 19
  • 22