1

What is the Best Way To Define Object Memeber and Please Explain Why

1 : 1st Way

var Obj = {
           M1 : 1,
           M2 : 2    
}

Using it like

 Obj.M1

2 :2nd Way

var Obj = function(){
 if (!(this instanceof Obj ))
            return new Obj ();
}
Obj.prototype.M1 =1 ;
Obj.prototype.M2 =2 ;

Using it Like

Obj().M1;

i mean with all that is using prototype better than defining the whole members with in these {} ?

Marwan
  • 2,362
  • 1
  • 20
  • 35
  • since 1st way you created an object literal, these are technically **instance variables**, not **member variables**, i believe.. (javascript as a prototypical language doesn't need classes to define object instances - see http://stackoverflow.com/questions/2800964/benefits-of-prototypal-inheritance-over-classical) – Aprillion Dec 16 '12 at 11:31
  • 3
    I Found Some Answers There http://stackoverflow.com/questions/4736910/javascript-when-to-use-prototypes http://stackoverflow.com/questions/12180790/defining-methods-via-prototype-vs-using-this-in-the-constructor-really-a-perfo http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript – Marwan Dec 16 '12 at 11:34

1 Answers1

4

That dependes whether you want to create multiple instances of Obj or just one. Aspects from class-based object oriented languages like inheritance are only possible when you use the second way (it's not real inheritance as you know it from class-based OO languages, but it's similar). Generally you can compare the first way with a static class in class-based OO programming languages in case you are more familiar with them.

Johannes Egger
  • 3,874
  • 27
  • 36
  • javascript is object-oriented, it's just a prototypical instead of classical programming language (doesn't use classes, but prototypes). – Aprillion Dec 16 '12 at 11:34