Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two ways of creating javascript objects, which one should I use?

Tags:

javascript

These are the ways of creating javascript objects:

function apple(optional_params) {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function() {
        return this.color + ' ' + this.type + ' apple';
    }
}

I really prefer the latter one most since it's Json syntax, but I've seen more of the first one than the latter one.

  • Are there any differences between them functionally?
  • Could each of them be extended, inherited and cloned/copied?
  • In the latter one I could easily create nested elements, is this possible with the first one?
  • In the latter one I can't pass optional parameters?
  • Are they serving different purposes? If yes, could you give scenarios where I would use either of them.
like image 692
never_had_a_name Avatar asked Sep 24 '10 06:09

never_had_a_name


People also ask

What are two ways to create objects using JavaScript?

There are four ways to create an object in JavaScript - using object literals, using the function constructor, using the Object. create method, and using the class keyword (which is almost the same as using a function constructor).

Which is the right option to create objects in JavaScript?

Creating object with Object. The Object. create() method creates a new object, using an existing object as the prototype of the newly created object.

What are the two kinds of objects properties we can have in JavaScript?

JavaScript objects have two types of properties: data properties and accessor properties.


1 Answers

The difference is that you can reuse the first one. Example:

function Apple(type, color) {
  this.type = type;
  this.color = color;
  this.getInfo = function () {
    return this.color + ' ' + this.type + ' apple';
  }
}

var red = new Apple("Macintosh", "red");
var green = new Apple("Granny Smith", "green");

vs.

var red = {
  type: "Macintosh",
  color: "red",
  getInfo: function() {
    return this.color + ' ' + this.type + ' apple';
  }
};

var green = {
  type: "Granny Smith",
  color: "green",
  getInfo: function() {
    return this.color + ' ' + this.type + ' apple';
  }
};
like image 108
Guffa Avatar answered Sep 27 '22 17:09

Guffa