1

In javascript what's the best way of declaring objects?

This one

var Class = function(){};

Class.prototype.print = function(){
    console.log('hello world');
};

or this one

var Class_2 = {};

Class_2.print = function(){
    console.log('hello world');
};

in which case I should use one method over another?

gaggina
  • 5,369
  • 10
  • 31
  • 31

2 Answers2

4

It depends if you want to create a class or a single object.

JavaScript OOP model is based on prototypes, not on classes. That's why you can add properties and methods not only to a class (meaning that all "instances" of that class will have that properties or method), but also to a particular object. So you could have object A and B instances of class C, and you could add special behavior to A that only A has, and B doesn't has it... All this sounds strange, because JavaScript doesn't actually have classes. It only has prototypes, and you can more or less "simulate" classes by using the things you can do with prototypes. In JavaScript when an object A is an "instance" of an other object B, you are actually saying that B is the prototype of A. That means that you'll define A based on the differences it has on B.

In real world that would mean that your first ever encounter with a Sheep, was with Dolly, a big, white, hairy sheep. So you say Dolly.color = white; Dolly.hair = a_lot; Dolly.size = big; Then somebody asks you what's the color of a Sheep, and since you only know Dolly, you think that all Sheeps are exactly like dolly and you answer white... Then you met another Sheep, Pete, but this one is black and big and hary. So you say that Pete is exactly like Dolly, except that Pete is black.... So you'll say that Pete.Prototype = Dolly ( That means that is exactly like dolly), but then you'll overwrite the color and say it's different: Pete.color = black;

To "simulate" Classes in JavaScript what you do is define an "Ideal" Sheep called Sheep that posses all the "default" qualities of all sheeps, and use that as a prototype for all the other sheeps.

There are many ways to define classes in JavaScript. But you should always remember that you aren't actually defining classes, but prototypes, and simulating classes. You'd better try learning about prototypes, if you really want to understand what is going on, and how to get the best out of it.

user1494736
  • 2,425
  • 16
  • 8
1

it depends on what are your purposes.

the first one can be instantiated

var obj = new Class('...');

and the second one can be used to take advantage of the namespace

Ibu
  • 42,752
  • 13
  • 76
  • 103