3 ways to create classes

Using a function

function Car(type) {
  this.type = type;
  this.color = 'red';
  this.getInfo = getCarInfo;
}

function getCarInfo() {
  return this.color + ' ' + this.type + ' car';
}

Usage

let car = new Car('diesel');
car.color = 'reddish';
alert(car.getInfo());

Methods defined internally

function Car(type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' car';
    };
}

Methods added to the prototype

function Car(type) {
    this.type = type;
    this.color = "red";
}

Car.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' car';
};

Using Object literals

Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:

let o = {};

instead of the "normal" way:

let o = new Object();

For arrays you can do:

let a = [];

instead of:

let a = new Array();

So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:

let car = {
    type: "diesel",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' car';
    }
}

In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.

car.color = "reddish";
alert(car.getInfo());

Singleton using a function

let car = new function() {
    this.type = "diesel";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' car';
    };
}

results matching ""

    No results matching ""