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 Answers 2
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();.
answered Oct 27, 2015 at 17:55
Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Bergi
This. See also Javascript: Object Literal reference in own key's function instead of 'this' for a comparison of the two approaches.
Bergi
Alternative 3: pass
this or this.a as a parameter to setupPagerThomas K. Nielsen
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.Yes, a could be a local variable
var StpTable = function () {
var a = 10;
function setupPager() {
...
if(i<a) {
...
}
...
};
return {
"a": a,
"init": function() {
setupPager();
}
}
}();
answered Oct 27, 2015 at 17:56
Jamiec
136k15 gold badges143 silver badges202 bronze badges
Comments
lang-js
StpTable?