Skip to content

Instantly share code, notes, and snippets.

@jrf0110
Created April 23, 2012 22:05
Show Gist options
  • Save jrf0110/2474199 to your computer and use it in GitHub Desktop.
Save jrf0110/2474199 to your computer and use it in GitHub Desktop.
Simple extendable classes in javascript
/* 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);​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment