OOP in JavaScript

JS OOP:

class Car {
  constructor(make) {
    this.make = make;
    this.isOn = false;
  }
  start() {
    this.isOn = true;
    console.log(`${this.make} started.`);
  }
  stop() {
    this.isOn = false;
    console.log(`${this.make} stopped.`);
  }
  isRunning() {
    return this.isOn;
  }
}
class ElectricCar extends Car {
  constructor(make, batteryCapacity) {
    super(make);
    this.batteryCapacity = batteryCapacity;
  }
  charge() {
    console.log(`${this.make} is charging.`);
  }
}
let myElCar = new ElectricCar('EV', '100 kWh');
myElCar.start(); // EV started.
console.log(myElCar.isRunning()); // true
myElCar.stop(); // EV stopped.
console.log(myElCar.isRunning()); // false
myElCar.charge(); // EV is charging.

JS OOP via prototype:

var Circle = { // Class
	area: function() {
		return this.radius * this.radius * Math.PI;
	}
}

var instance = { radius:5 };
instance.__proto__ = Circle; // inheritance via prototype, does not work in IE

console.log( instance.area() ); // prints '78.5398'

js:

function Circle(radius) { // Class
	this.radius = radius;
}
Circle.prototype.area = function() {
	return this.radius * this.radius * Math.PI;
}
var instance = new Circle(5);
console.log( instance.area() ); // prints '78.5398'

Data and access properties

var createPerson = function(firstName, lastName) {
  var person = {};
 
  Object.defineProperties(person, {
    firstName : {
      value : firstName,
      writable : true
    },
    lastName : {
      value : lastName,
      writable : false
    },
    fullName : {
      get : function() { 
        return this.firstName + ' ' + this.lastName; 
      },
      set : function(value) { 
        this.firstName = value + ' set ';
        this.lastName = value + ' set ';
      }
    }
  });
 
/*  Object.defineProperty(person, "firstName", {
    value : firstName,
    writable : true
  });
 
  Object.defineProperty(person, "lastName", {
    value : lastName,
    writable : false
  });
*/
 
  return person;
};
 
var person = createPerson("John", "Doe");
//person.firstName = 'Jane'; // sets firstName to 'Jane'
//person.lastName = 'New'; // cannot set lastName
//person.fullName = 'New'

Leave a Comment