brain storm
brain storm

Reputation: 31272

Why does this javascript object behave differently with and without a module pattern?

I have the following code with and without a module pattern. I have given the results right next to the execution. In the module pattern, I am able to change foo and set_inner, while in the function object (non-module), I can't change foo and set_inner.

module pattern:
var someObj = (function () {
     var instance = {},         
     inner = 'some value';      
     instance.foo = 'blah';      
     instance.get_inner = function () {         
         return inner;     };      
     instance.set_inner = function (s) {        
         inner = s;     };     
     return instance; })(); 

someObj.get_inner();//some value
someObj.set_inner("kkkk");
someObj.get_inner();//kkk
someObj.foo;//blah
someObj.foo="ddd";
someObj.foo;//ddd

non-module:
var someObj = function () {     
    var instance = {},         
    inner = 'some value';      
    instance.foo = 'blah';      
    instance.get_inner = function () {        
        return inner;     };      
    instance.set_inner = function (s) {         
        inner = s;     };      
    return instance; }; 

someObj().get_inner();//some value 
someObj().foo;//blah 
someObj.foo="aaa"; 
someObj().foo;//blah 
someObj().set_inner("kkk"); 
someObj().get_inner();//some value 

Any help is much appreciated. Thanks!

Upvotes: 0

Views: 46

Answers (1)

James Allardice
James Allardice

Reputation: 166061

Your "module" example creates a single object, referred to by instance. The anonymous function is immediately invoked, and returns that object. So someObj refers to instance.

Your "non-module" example creates a new object each time you invoke it. The anonymous function is not immediately invoked. Instead, it has to be called every time you want to use it.

It would behave the same way if you assigned the return value to a variable and referred to that, instead of repeatedly invoking someObj:

var obj = someObj();
obj.get_inner(); //some value
obj.foo; //blah
obj.foo="aaa";
obj.foo; //aaa
//etc...

Upvotes: 2

Related Questions