Thomas K. Nielsen
Thomas K. Nielsen

Reputation: 27

How to reference internally in javascript objects

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?

Upvotes: 0

Views: 39

Answers (2)

Jamiec
Jamiec

Reputation: 136239

Yes, a could be a local variable

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

  return {

    "a": a,

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

}();

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817208

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();.

Upvotes: 3

Related Questions