Best Way to Implement a Class

by Sukanya Halder

HTML

<!-- Notes : Best Way to implement a class
This class is wrapped in an IIFE. The wrapper encapsulates the function and the Vehicle
prototype. There is no attempt to make the data private. The code works as follows.
■■ When the code is loaded into the browser, the IIFE is immediately invoked.
■■ A nested function called Vehicle is defined in the IIFE.
■■ The Vehicle function’s prototype defines getInfo and startEngine functions that are on
every instance of Vehicle.
■■ A reference to the Vehicle function is returned, which is assigned to the Vehicle
variable.
 
This is a great way to create a class, and all future class examples use this pattern.
-->

JavaScript

var car;
var Vehicle = (function () {
    function Vehicle(year, modelname) {
        var model = modelname;
        var modelmakeyear = year;
        this.makemodel = function () {
            return model;
        };
        this.makeyear = function () {
            return modelmakeyear;
        };
    }
    Vehicle.prototype.show = function () {
        console.log(this.makemodel() + "--" + this.makeyear());
    };
    return Vehicle;
})();

car = new Vehicle("BMW", "2015");
car2 = new Vehicle("Mercedes", "2015");
car.show();
car2.show();