Hi I’m using this module pattern variant and I’m looking for the best way to get access to a parent object. I realise there is no way to know what parents an object has so I want to include some context in the constructor. I thought this would work but it doesn’t, any ideas?
$(document).ready(function(){
var main = new Main();
});
function Main() {
var one = 'hello';
init();
function init() {
var data = new Data(this);
var two = data.load();
console.log(one+' '+two);
data.output();
}
}
function Data(context) {
// public vars / methods
var pub = {
'load' : function() {
return ('world');
},
'output' : function() {
var one = context.one // <-- what should this be?
var two = this.load();
console.log (one+' '+two);
}
}
return pub;
}
The output is:
hello world
undefined world
When you call a constructor function with the
newoperator, you are basically doing something likeWhen you declare a private variable with
varit will just be a plain variable and nothing else. If you want to add things to thethisyou need to do so explicitelyBut that is not all!
thisis not lexically scoped so the init function gets its own otherthisthat is unrelated to thethisfrom outside (this explains theundefinedyou get). When you want to usethisin an inner function you need to do a workaround, like in:That said, just by your example I don’t see why you need to do all of this. I prefer to use constructor functions (and
new) only when strictly necessary (when I want to make use of prototypal inheritance). In your case perhaps you can get away with a “less OO” approach?