javascript - Difference of method calling between object and function -


here code , 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 difference between these 2 ways of method calling. have make test2 inmmediate invoke function execution make sure works. mean carry coals newcastle? 1 better or situation should use them?

hey lads, what's difference between these 2 ways of method calling.

there's no significant difference between 2 resulting objects have them.

which 1 better or situation should use them?

the second scheme offers option of having private variables in closure methods use 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 use second scheme when needed these private variables. otherwise, first option bit simpler , involves 1 less function call.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -