0

Here is the code and fiddle:

var test = {
    value : "sss", 
    func1 : function(){
        console.log(this.value);
    }   
};

var test2 = function(){
    return {
        value : "sss",
        func1 : function(){
            console.log(this.value);
        }
    };
}();

test.func1();
test2.func1();

Hey lads, what's the difference between these two ways of method calling. I have to make test2 as Inmmediate Invoke Function Execution to make sure it works. Does it mean carry coals to Newcastle? Which one is better or what situation should I use them?

Community
  • 1
  • 1
SPG
  • 6,109
  • 14
  • 48
  • 79

3 Answers3

2

Hey lads, what's the difference between these two ways of method calling.

There's no significant difference between the two resulting objects as you currently have them.

Which one is better or what situation should I use them?

The second scheme offers you the option of having some private variables in the closure that your methods could use like this:

var test2 = function(){
    var cnt = 0;
    return {
        value : "sss",
        func1 : function(){
            console.log(this.value);
        },
        getCnt: function() {
            return ++cnt;
        }
    };
}();

test2.getCnt();    // 1
test2.getCnt();    // 2

You would use the second scheme when you needed these private variables. Otherwise, the first option is a bit simpler and involves one less function call.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

In the first approach, if you assign it to a prototype it would overwrite your constructor with the global Object. That would be something to watch out for.

You don't have that issue with the second approach.

Here's a post I wrote that discusses that at length: https://codereview.stackexchange.com/questions/62402/javascript-constructor-and-namespace-in-object-literal-style/86222#86222

Community
  • 1
  • 1
shmuli
  • 5,086
  • 4
  • 32
  • 64
0

The first one is simple object literal with defined properties and methods. See: Object Literals

The second one is Immediately-Invoked Function Expression (IIFE) returning an object literal with it's properties and methods.

It is meter of current situation when you would like to use one the other but the second one enables you to have private "stuff" and is used for Revealing Module Pattern.

Andrej Kaurin
  • 11,592
  • 13
  • 46
  • 54