Created
May 15, 2012 18:12
-
-
Save n8agrin/2703866 to your computer and use it in GitHub Desktop.
A simple, if old, class system for Javascript.
This file contains hidden or 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
// The best javascript class system ever! This is old news to most, but | |
// more and more I find myself coming back to this. I don't have a vendetta | |
// against the `new` keyword. I just sometimes want encapsulation in a way | |
// that doesn't feel like a complete hack. | |
// Start with a closure | |
var vehicle = function() { | |
// Use Object.create | |
var vehicle = Object.create({}); | |
// Public properties | |
vehicle.terrain = null; | |
// True encapsulation! | |
var wheels = 0; | |
// Add some methods | |
vehicle.wheels = function() { | |
return wheels; | |
} | |
vehicle.setWheels = function(count) { | |
wheels = count; | |
return this; | |
} | |
// For the sake of demonstrating 'super-like' behavior | |
vehicle.whoAmI = function() { | |
return "vehicle"; | |
} | |
return vehicle; | |
} | |
// Create a subclass | |
var car = function() { | |
var car = Object.create(vehicle()); | |
car.terrain = 'ground'; | |
// Wheels on the car go round and round | |
car.setWheels(4); | |
// Who you be? | |
car.whoAmI = function() { | |
return "car"; | |
} | |
return car; | |
} | |
// Usage | |
var mycar = car(); | |
// Returns '4' | |
mycar.wheels(); | |
// Returns 'car' | |
mycar.whoAmI(); | |
// Returns 'vehicle', Super-like behavior! | |
Object.getPrototypeOf(mycar).whoAmI(); | |
// Returns 'ground' | |
mycar.terrain; | |
// Returns 'null' | |
Object.getPrototypeOf(mycar).terrain; | |
// If you're worried about this being portable... | |
// From https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create | |
if (!Object.create) { | |
Object.create = function (o) { | |
if (arguments.length > 1) { | |
throw new Error('Object.create implementation only accepts the first parameter.'); | |
} | |
function F() {} | |
F.prototype = o; | |
return new F(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment