I’m trying to set the value of a private variable through a module pattern.
So what I’m saying is set $content to the value I’m passing to person.content. But this doesn’t seem to work because when I do an alert on the value it gives me an undefined error.
$(document).ready(function(){
person.content = $('#content');
person.getContent();
});
// Person Module
var person = ( function(){
var $content;
function getContent(){
alert( 'content = '+$content.find(':first h2').text());
}
return {
content: $content,
getContent : getContent,
}
}( ) );
Your problem is that when you say this:
You’re not altering the
var $content;inside the function, you’re just changing the value of thecontentproperty inperson. Then, when you say this:The inner
getContentfunction will be using the (uninitialized)var $contentinside the outer function. You’ll need to add asetContentfunction:And make sure you don’t leave that trailing comma in your return object, most (all?) versions of IE get upset about that.
And then, elsewhere:
Depending on your target browsers and versions, you could define getter and setter functions for the properties on your returned object:
__defineSetter__examplegetexample.But using an explicit mutator function will work everywhere.