oop - JavaScript - Different ways to construct objects -


while reading other people's source code , various articles on web, found when different people use "object-oriented-style" programming in javascript, quite differently.

suppose, want create tiny module having 1 property , 1 function. i've seen @ least 4 approaches task:

// option 1 var myobject1 = {     myprop: 1,     myfunc: function () { alert("myprop has value " + this.myprop); } };  // option 2 var myobject2 = function () {     return {         myprop: 1,         myfunc: function () { alert("myprop has value " + this.myprop); }     }; }();  // option 3 var myobject3 = function () {     this.myprop = 1;     this.myfunc = function () { alert("myprop has value " + this.myprop); } }; var myobject3 = new myobject3();  // option 4 var myobject4 = function () { }; myobject4.prototype.myprop = 1; myobject4.prototype.myfunc = function () { alert("myprop has value " + this.myprop); }; var myobject4 = new myobject4(); 

all these approaches syntactically different seem produce objects can used in same way.

what's semantic difference between them? there cases when reason should choose 1 of these options on rest?

myobject1 object literal (singleton). useful in cases want have 1 object of type. @ static object.

myobject2 returns object literal. right after doing var foo = myobject2(), variable foo hold result { myprop: 1, myfunc: function(){...} } reference parent function has executed. called closure. can used define public api or modules, example.

i.e.:

var foo = (function(){      var privateprop = "i private property";       // object below returned, privateprop accessible       // through foo.publicprop      return {         publicprop: privateprop                  } })(); 

the privateprop property accessible through foo.publicprop.

myobject3 , myobject4 constructor functions. using new keyword before function call, tell javascript create instance of object. means every new object created way inherit properties , methods object definition.

the difference between myobject3 , myobject4 in case of former, every instance of object have its own copy of myprop , myfunc properties, whereas latter reference properties. means no matter how many instances of object myobject4 create, there 1 of myprop , myfunc.

i recommend on how closures, prototypal inheritance, , several object design patterns (modules, etc.) work in javascript.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -