0

I am new to this and can't figure this out. I have this simplified piece of code:

var StpTable = function () {

  function setupPager() {
    ...
    if(i<StpTable.a) {
      ...
    }
    ...
  };

  return {

    "a": 10,

    "init": function() {
      setupPager();
    }
  }

}();

How do I from with the setupPager() function reference the variable a without having to use the variable name StpTable. Tried with this.a but the scope is off.

Any suggestions?

  • What's wrong with using `StpTable`? – Bergi Oct 27 '15 at 18:01
  • That's a good question. It works! It is not pretty - in my eyes - using the external name in an internal reference. But maybe it's my head that's twisted. This is new to me in javascript :-) – Thomas K. Nielsen Oct 27 '15 at 18:08

2 Answers2

3

Assign the object to a local variable before you return it and use that.

var StpTable = function () {

  function setupPager() {
    ...
    if(i<obj.a) {
      ...
    }
    ...
  };

  var obj = {

    "a": 10,

    "init": function() {
      setupPager();
    }
  };

  return obj;

}();

Or simply assign the function as property of the object:

var StpTable = function () {

  function setupPager() {
    ...
    if(i<this.a) {
      ...
    }
    ...
  };

  return {

    "a": 10,

    "init": setupPager,
  };

}();

Then this.a will work, assuming the function is called with StpTable.init();.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • This. See also [Javascript: Object Literal reference in own key's function instead of 'this'](http://stackoverflow.com/q/10711064/1048572) for a comparison of the two approaches. – Bergi Oct 27 '15 at 18:01
  • Alternative 3: pass `this` or `this.a` as a parameter to `setupPager` – Bergi Oct 27 '15 at 18:02
  • The `obj` idea is good. It works like a charm. I like it. My `init` function does several other things in my real code so the 2nd alternative becomes a little more complicated. The 3rd is also not so easy in the real code. I have several of these vars that I want to reference from within the object, so the first one is clean and simple to me. Thx. – Thomas K. Nielsen Oct 27 '15 at 18:12
0

Yes, a could be a local variable

var StpTable = function () {
  var a = 10;
  function setupPager() {
    ...
    if(i<a) {
      ...
    }
    ...
  };

  return {

    "a": a,

    "init": function() {
      setupPager();
    }
  }

}();
Jamiec
  • 133,658
  • 13
  • 134
  • 193