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?

2
  • What's wrong with using StpTable? Commented Oct 27, 2015 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 :-) Commented Oct 27, 2015 at 18:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

This. See also Javascript: Object Literal reference in own key's function instead of 'this' for a comparison of the two approaches.
Alternative 3: pass this or this.a as a parameter to setupPager
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.
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();
    }
  }

}();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.