Creating New Objects in JavaScript
- by Ken Ray
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:
Which way is "better"?
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?
If I want to create an array of
these objects, are there any other
considerations?
Thanks in advance.