Monday, May 20, 2024
44
rated 0 times [  51] [ 7]  / answers: 1 / hits: 26878  / 14 Years ago, fri, april 16, 2010, 12:00:00

I'm a relatively newbie to object oriented programming in JavaScript, and I'm unsure of the best way to define and use objects in JavaScript. I've seen the canonical way to define objects and instantiate a new instance, as shown below.



function myObjectType(property1, propterty2) {
this.property1 = property1,
this.property2 = property2
}
// now create a new instance
var myNewvariable = new myObjectType('value for property1', 'value for property2');


But I've seen other ways to create new instances of objects in this manner:



var anotherVariable = new someObjectType({
property1: Some value for this named property,
property2: This is the value for property 2
});


I like how that second way appears - the code is self documenting. But my questions are:




  1. Which way is better?


  2. Can I use that second way to
    instantiate a variable of an object
    type that has been defined using the
    classicalway of defining the
    object type with that implicit
    constructor?


  3. If I want to create an array of
    these objects, are there any other
    considerations?




Thanks in advance.


More From » javascript-objects

 Answers
10

It's really down to taste. This way:



var anotherVariable = new someObjectType({
property1: Some value for this named property,
property2: This is the value for property 2
});


... is generally better if there's more than 2/3 arguments, as it aids readability and makes it easier to avoid the optional argument problem (fn(null,null,null,123')).



Another consideration is performance. Passing arguments in the conventional way will be faster, but this speed gain only becomes significant in very performance-sensitive situations.




Can I use that second way to instantiate a variable of an object type that has been defined using the classicalway of defining the object type with that implicit constructor?




Not easily. If you want to instantiate a constructor by using a hash instead of just passing arguments, and you don't have control over the source, then you could wrap it:



var _constructor = SomeConstructorFunction;

SomeConstructorFunction = function(hash) {
return new _constructor(hash.property1, hash.property2);
};


I wouldn't really recommend messing with third-party APIs just for the sake of style though.




If I want to create an array of these objects, are there any other considerations?




How big is the array? What's the array for exactly? Performance might be worth considering...


[#97053] Tuesday, April 13, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marvinm

Total Points: 406
Total Questions: 104
Total Answers: 121

Location: Iceland
Member since Tue, Jan 25, 2022
2 Years ago
;