Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

So far I saw three ways for creating an object in JavaScript. Which way is best for creating an object and why?

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

In the second and third way, the name of the object is in upper-case whereas in the first way the name of the object is in lower-case. What case should we use for an object name?

First way:

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."); 

Second way:

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

Third way — JavaScript objects using array syntax:

var NewObject = {};  NewObject['property1'] = value; NewObject['property2'] = value; NewObject['method'] = function(){ /* function code here */ } 
like image 364
Jamna Avatar asked Jul 27 '11 12:07

Jamna


People also ask

What is the best way to create object in JavaScript?

Using an Object Literal This is the easiest way to create a JavaScript Object. Using an object literal, you both define and create an object in one statement. An object literal is a list of name:value pairs (like age:50) inside curly braces {}.

Which of these is the correct way to initialize an object variable in JavaScript?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).

What are object properties in JavaScript?

An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.


2 Answers

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 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; 
like image 194
Felix Kling Avatar answered Sep 23 '22 03:09

Felix Kling


There is various way to define a function. It is totally based upon your requirement. Below are the few styles :-

  1. Object Constructor
  2. Literal constructor
  3. Function Based
  4. Protoype Based
  5. Function and Prototype Based
  6. Singleton Based

Examples:

  1. Object constructor
var person = new Object();  person.name = "Anand", person.getName = function(){   return this.name ;  }; 
  1. Literal constructor
var person = {    name : "Anand",   getName : function (){    return this.name   }  }  
  1. function Constructor
function Person(name){   this.name = name   this.getName = function(){     return this.name   }  }  
  1. Prototype
function Person(){};  Person.prototype.name = "Anand"; 
  1. Function/Prototype combination
function Person(name){   this.name = name; }  Person.prototype.getName = function(){   return this.name }  
  1. Singleton
var person = new function(){   this.name = "Anand" }  

You can try it on console, if you have any confusion.

like image 25
Anand Deep Singh Avatar answered Sep 20 '22 03:09

Anand Deep Singh