Last active
August 29, 2015 14:10
-
-
Save webdesserts/a666fa2d93386e3a6ee6 to your computer and use it in GitHub Desktop.
Prototype .create() pattern
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
// create a "Class-like" object | |
Point = {} | |
// create an object like this one, but with a clean state | |
Point.create = function create () { | |
new_shape = Object.create(this) | |
new_shape.init.apply(new_shape, arguments) | |
return new_shape | |
} | |
// initialize all state | |
Point.init = function init (x, y) { | |
this.x = x | |
this.y = y | |
} | |
Point.move = function move (x, y) { | |
this.x += x | |
this.y += y | |
} | |
// creates a point with an x & y of 5 | |
point = Point.create(5, 5) | |
point.x // 5 | |
point.y // 5 | |
// Or we can create more "Class-like" structures | |
Shape = Object.create(Point) | |
// add some extra state to Shape without affecting state on Point | |
Shape.init = function (x, y, width, height) { | |
// do everything our prototype does | |
Object.getPrototypeOf(Shape).init.call(this, x, y) | |
// and add some extra state | |
this.width = width | |
this.height = height | |
} | |
// and of course, we can continue to the prototype chain | |
square = Shape.create(1, 1, 20, 20) | |
// what's even cooler, is that since every object inherits the create method | |
// every object is a "Class"! | |
cube = square.create(9, 9, 30, 30) | |
cube.x = 9 | |
cube.depth = 30 | |
// and we can still use methods defined further up the chain | |
cube.move(-5, -5) | |
cube.x // 4 | |
cube.y // 4 | |
// ...or write our own version | |
cube.move = function (x, y, z) { | |
Object.getPrototypeOf(this).move.call(this, x, y) | |
this.z += z | |
} | |
cube.move(-1, 1, -2) | |
cube.x // 3 | |
cube.y // 5 | |
cube.z // 6 | |
// Oh and since our "Classes" are just objects. We can use them as such. | |
Shape.init(5, 20) | |
Shape.x // 5 | |
Shape.y // 20 | |
Shape.move(5, 0) | |
Shape.x // 10 | |
Shape.y // 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment