Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript fast prototypal inheritance?

Tags:

javascript

I'm learning JavaScript, and I've found its prototypal inheritance WAY too verbose. So I searched a bit for alternatives, but everything I found used closures and degraded performance significantly because of that.

I tried writing my own and it seems to work. Maybe I misunderstood something, or maybe this is regarded as bad practice for some reason. Can someone with a bit more experience share his thoughts about this approach?

var Class = {
  constructor: function() {},
  extend: function(properties) {
    var base = this.prototype || Class;
    var constructor = properties.hasOwnProperty('constructor') ?
      properties.constructor : base.constructor;
    constructor.base = base;
    constructor.prototype = Object.create(base);
    constructor.extend = Class.extend;
    for(var p in properties) {
      constructor.prototype[p] = properties[p];
    }
    constructor.prototype.constructor = constructor;
    return constructor;
  }
};

Live demo: http://jsfiddle.net/xNGAB/

Performance: http://jsperf.com/object-construction99/2

EDIT: One thing I still find clumsy is the calls to base class functions, such as C.base.constructor.call(this);. I don't really understand why this doesn't get properly bound when we do C.base.constructor().

like image 996
Giovanni Funchal Avatar asked Apr 08 '26 04:04

Giovanni Funchal


1 Answers

You should take a look at CoffeeScript. It has Ruby-like syntax and compiles into JavaScript. The best part is you can implement prototype inheritance like this (from their user manual):

class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
like image 115
Jivings Avatar answered Apr 10 '26 18:04

Jivings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!