2

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,

        }

    }( ) );
mu is too short
  • 426,620
  • 70
  • 833
  • 800
Chapsterj
  • 6,483
  • 20
  • 70
  • 124

2 Answers2

5

Your problem is that when you say this:

person.content = $('#content');

You're not altering the var $content; inside the function, you're just changing the value of the content property in person. Then, when you say this:

person.getContent();

The inner getContent function will be using the (uninitialized) var $content inside the outer function. You'll need to add a setContent function:

var person = (function(){
    var $content;
    function setContent(c) {
        $content = c;
    }
    // ...
    return {
        setContent: setContent,
        getContent: getContent
    };
}());

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:

person.setContent($('#content'));
person.getContent();

Depending on your target browsers and versions, you could define getter and setter functions for the properties on your returned object:

But using an explicit mutator function will work everywhere.

Community
  • 1
  • 1
mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

Think of values in object like pointers.

person is an object where the content property points to the $content value in the closure. When you do person.content = somethingElse then you are setting the content property of the person object to point to somethingElse instead.

Taking the closure out of it, this illustrates the same thing:

var a = 'a';
var b = 'b';

var obj = { a: a }
alert(obj.a) // "a"

obj.a = b;
alert(obj.a) // "b"
alert(a) // "a"

Setting an objects property to a new object, never does anything to the object that used to be assign there. It simply points to a new and different object instead.

The only way to assign this inner private variable is from inside the closure, like say in a setContent method.

return {
  getContent: function() { return $content; },
  setContent: function(val) { $content = val; }
};
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337