Onyx
Onyx

Reputation: 5782

2 ways of creating an object, not sure what the difference is or which one to use

Usually, I create a class and then instantiate objects from that class, however, as I was watching a tutorial I saw the guy creating objects just by using a function without even having a class.

In the code below I have used both ways just to check what the difference would be when I console log the arrays that contain the objects. I fill the first array with objects generated using my class and the second array with the objects generated by the function.

After I console.log() both arrays, they seem to be identical. So what is the point of creating a class if I can create objects without having it?

var w = 40;
var cols, rows;
var grid = [];
var grid1 = [];

class Cell {
    constructor(i, j) {
        this.i = i,
        this.j = j
    }
}

function Cell2(i, j) {
    this.i = i;
    this.j = j;
}

function setup() {
    createCanvas(400, 400);
    cols = floor(width/w);
    rows = floor(height/w);

    for (var i = 0; i < cols; i++) {
        for (var j = 0; j < rows; j++) {
            var cell = new Cell(i,j);
            grid.push(cell);
        }
    }

    for (var i = 0; i < cols; i++) {
        for (var j = 0; j < rows; j++) {
            var cell1 = new Cell2(i,j);
            grid1.push(cell1);
        }
    }
}

Upvotes: 0

Views: 36

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138557

The class syntax is just syntactic sugar. JavaScript doesn't really have class inheritance, it has prototypal inheritance with constructor functions. But that confused a lot of people, especially those coming from a class based language, and therefore the class keyword was added to make that more familiar. And actually I really like it:

  // new ES 6 syntax
  class Child extends Parent {
   constructor() { 
     super();
   }

   method() {
     super.method();
   }

  static staticMethod() { }
}

 // equals the old one:
 function Child() {
   Parent.call(this);
   // constructor...
 }

 Child.staticMethod = function() { /*...*/ };

 Child.prototype.method = function() {
   Parent.prototype.method.call(this);
 };

Upvotes: 1

Manish Gharat
Manish Gharat

Reputation: 420

There is no such thing as a class in Javascript. Javascript is not Object Oriented. Javascript follows a prototype pattern. the class you create in Javascript is just a syntactical sugar, created to make it easier for developers who are used to Object-oriented development

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Upvotes: 0

Related Questions