Jamna Jamna - 8 days ago 6
Javascript Question

Which way is best for creating an object in javascript? is "var" necessary before variable of object?

So far I saw three ways for creating a object in JavaScript, which way is best for creating a object and why?

I also saw that in all of these examples the keyword "var" is not used before property, why? is it not necessary to declare "var" before the name of a property as it mentioned that Properties are variables.

I forgot to ask one more thing:

In way2 and way3 the name of object is in uppercase where is in way1 the name of object is in lower case... what case we should use for an object name?

way 1

function person(fname,lname,age,eyecolor)
{
this.firstname=fname;
this.lastname=lname;
this.age=age;
this.eyecolor=eyecolor;
}

myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");


way 2

var Robot =
{
metal: "Titanium",
killAllHumans: function()
{
alert("Exterminate!");
}
};
Robot.killAllHumans();


way 3 (JavaScript objects using array syntax):

var NewObject = {};
NewObject['property1'] = value;
NewObject['property2'] = value;
NewObject['method'] = function(){ /* function code here */ }

Answer

There is no best way, it depends on your use case.

  • Use way 1 if you want to create several similar objects. In your example, Person (you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages.
  • Use way 2 if you only need one object of a kind (like a singleton). If you want this object to inherit from another one, then you have to use a constructor function though.
  • Use way 3 if you want to initialize properties of the object depending on other properties of it or if you have dynamic property names.

Update: As requested examples for the third way.

Dependent properties:

The following does not work as this does not refer to book. There is no way to initialize a property with values of other properties in a object literal:

var book = {
    price: somePrice * discount,
    pages: 500,
    pricePerPage: this.price / this.pages
};

instead, you could could do:

var book = {
    price: somePrice * discount,
    pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;

Dynamic property names:

If the property name is stored in some variable or created through some expression, then you have to use bracket notation:

var name = 'propertyName';

// the property will be `name`, not `propertyName`
var obj = {
    name: 42
}; 

// same here
obj.name = 42;

// this works, it will set `propertyName`
obj[name] = 42;