Skip to content

Instantly share code, notes, and snippets.

@michealbenedict
Created November 25, 2011 20:12
Show Gist options
  • Save michealbenedict/1394330 to your computer and use it in GitHub Desktop.
Save michealbenedict/1394330 to your computer and use it in GitHub Desktop.
Ruby-style classes in ECMAScript 5
var Class = Object.create(null, {
"new": {
"value": function () {
var result = Object.create(this, {
"class": {
"value": this
}
});
result.initialize.apply(result, arguments);
return result;
}
},
"initialize": {
"value": function () {},
"enumerable": true,
"configurable": true,
"writable": true
}
});
var Person = Class.new();
Person.initialize = function (name, age) {
this.name = name;
this.age = age;
}
Person.speak = function (message) {
return this.name + ": " + message;
};
var kit = Person.new("Kit", 18);
kit.speak("Hiya!");
Person.class === Class;
kit.class === Person;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment