public
Last active

Simple extendable classes in javascript

  • Download Gist
class.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/* This WAS a two-line function until an awesome reddit user pointed out my logical flaw. Now It's a 5-line function :( */
 
var Class = function(d){
d.constructor.extend = function(def){
for (var k in d) if (!def.hasOwnProperty(k)) def[k] = d[k];
return Class(def);
};
return (d.constructor.prototype = d).constructor;
};
 
var Node = Class({
constructor: function(n, w){
this.neighbors = n || [];
this.weights = w || [];
return this;
}
, addNeighbor: function(neighbor, weight){
neighbor.neighbors.push(this);
neighbor.weights.push(weight);
this.neighbors.push(neighbor);
this.weights.push(weight);
return this;
}
});
 
var Nooode = Node.extend({
constructor: function(n, w){
this.neighbors = n || [];
this.weights = w || [];
this.poop = "lakjsdflkjaskdflajsdlf";
return this;
}
});
 
var myNode = new Node();
myNode.addNeighbor(new Node(), 5);
var myNooode = new Nooode();
myNooode.addNeighbor(myNode, 2);‚Äč

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.