简体   繁体   中英

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!

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM