Skip to content

Instantly share code, notes, and snippets.

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

##Classical Inheritance emulation experiments in Javascript. the first 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 first one:

Global Function 'Extends';

function Extends(x,z){
	return z.prototype = new x;
}

This approach works more like a Decorator or a MixIn, but i like the syntax. When I started developing an framework called Supra that is MVC based, I thought that would be cool if I were able to have Controllers and Models APIs based on rails or cakephp, where we have your Controller extending AppController extending Controller Class and because of this, I began to seek ways to emulate classical inheritance in javascript.

...this was the first one that worked for a while...

How it works?:

//First the main 'Class' declaration...
function Foo(name){
    this.name = name;
    this.sayName = function(){
    console.log(this.name);
  }
}
//...and than the 'Class' that derivates from it.
Extends(Foo,Bar = function(name){
  this.name = name;
  this.newMethod = function(attr){
    console.log(attr);
  }
});

var FooInstance = new Foo('Alice')
var BarInstance = new Bar('Willian')

FooInstance.sayName(); //Alice
BarInstance.sayName(); //Willian

BarInstance.newMethod('test'); //test

Pros

  • Simple
  • lightweight
  • works well in so many tiny cases
  • Just my opinion : I like the syntax.

Cons

  • No interface protection
  • Poor Contructor manipulation

Give it a Chance .... just one line ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment