erikpalla
2/25/2017 - 6:41 PM

Object Oriented JavaScript

Object Oriented JavaScript

//functional creation of classes
var Car = function(){
  var obj = {loc: loc};
  obj.move = function(){
    obj.loc++;
  }
  return obj;
}

var Van = function(loc){
  var obj = Car(loc);
  obj.grab = function(){ /*...*/ }
  return obj;
}

var Cop = function(loc){
  var obj = Car(loc);
  obj.call = function(){ /*...*/ }
  return obj;
};

var john = Van(2);
//prototypal Classes
var Car = function(loc){
  var obj = Object.create(Car.prototype);
  obj.loc = loc;
  return obj;
}

Car.prototype.move = function(){
  this.loc++;
}

var john = Car(2);

//pseudoclassical Classes
var Car = function(loc){
  this.loc = loc;
}
Car.prototype.move = function(){
  this.loc++;
}

var Van = function(loc){
  //subclass
  Car.call(this, loc);
}
Van.prototype = Object.create(Car.prototype); //in past was used Van.prototype = new Car(); => broken pattern
Van.prototype.constructor = Van;
Van.prototype.grab = function(){ /*...*/ };

var john = new Car(2);
var amy = new Van(2);

//decorator functions
var carlike = function(obj, loc){
  obj.loc = loc;
  return obj;
}

var amy = carlike({}, 1);

//rewriting of behaviour of 'new' keyword
function spawn(constructor){
  var obj = {};
  Object.setPrototypeOf(obj, constructor.prototype);
  var argsArray = Array.prototype.slice.apply(arguments);
  return constructor.apply(obj, args.slice(1) || obj)
}
function Person(saying){
  this.saying = saying;
}
Person.prototype.talk = function(){
  console.log('I say:', this.saying)
}
var test = spawn(Person, "some text here");
test.talk()
class Dog extends Animal {
  // ...
}

class Cat extends Hostile(Animal) {
  // ...
}

class HostileRobot extends Hostile(Robot) {
  // ...
}

class Cat extends Demonic(Hostile(Mammal(Animal))) {
  // ...
}

class Robot extends Hostile(Object) {
  // ...
}