Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guisouza/8c592323f833d981cf1c to your computer and use it in GitHub Desktop.
Save guisouza/8c592323f833d981cf1c to your computer and use it in GitHub Desktop.
Classical Inheritance emulation experiments in Javascript. the second one

##Classical Inheritance emulation experiments in Javascript. the Second one

(just because I like it)

I've been experimenting different ways to emulate classical inheritance in javascript and I will daily publish insights about some experiments that I've been doing in the last months till I reach a stable and usable solution for this inexistent problem.

The Second one:

The "Class" 'Class';

function Class(){}

Class.Extends = function(props){

  var Parent = this;
  var proto;

  Parent['extending'] = true;
  proto = new Parent();
  delete Parent['extending'];

  for (prop in props){
    proto[prop] = props[prop]
  }

  function Class (){
    if (!Class['extending'] && typeof proto.init == 'function'){
      proto.init.apply(this,arguments);
    }
  }

  Class.prototype = proto;
  Class.prototype.constructor = Class;

  Class.Extends = Parent.Extends;
  return Class
}

This approach works well in 90% of the cases and emulates the Classical inheritance in a really elegant way. Different from the previous example this is not just an workaround. It has constructor manipulation (the init method) and takes care of the prototype so you can play with instanceof in the child classes.

How it works?:


var Food = Class.Extends({
  init:function(){
    this.food = Math.floor(Math.random()*10);
  },
  eaten:function(){
    this.food = 0;
  }
})

var Fish = Food.Extends({
  init:function(){
    this.food = Math.floor(Math.random()*10);
  }
})



var Animal = Class.Extends({
  init:function(){
    this.hungry = 100;
  },
  eat:function(food){
    if (food instanceof Food){
      this.hungry = this.hungry - food.food;
      console.log(this.hungry)
      food.eaten();
    }else{
      console.log('this is not edible')
    }

  }
})

var Cat = Animal.Extends({
  init:function(name){
    this.name = name;
    this.hungry = 100;
  }
})

var anAnimal = new Animal; //init Animal
var steveTheCat = new Cat('Steve');

steveTheCat.eat(new Fish);
steveTheCat.eat(new Food);
anAnimal.eat(steveTheCat); //this is not edible



We are almost there ! =D

Pros

  • Almost simple
  • Lightweight
  • Works in 90% of the cases
  • Constructor control =]

Cons

  • Poor Super access
  • No interface protection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment