Creating New Objects in JavaScript

Posted by Ken Ray on Stack Overflow See other posts from Stack Overflow or by Ken Ray
Published on 2010-04-16T13:40:07Z Indexed on 2010/04/16 13:43 UTC
Read the original article Hit count: 254

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 "classical"way 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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-objects