Created
November 25, 2011 20:12
-
-
Save michealbenedict/1394330 to your computer and use it in GitHub Desktop.
Ruby-style classes in ECMAScript 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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