Skip to content

Instantly share code, notes, and snippets.

@webdesserts
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdesserts/a666fa2d93386e3a6ee6 to your computer and use it in GitHub Desktop.
Save webdesserts/a666fa2d93386e3a6ee6 to your computer and use it in GitHub Desktop.
Prototype .create() pattern
// create a "Class-like" object
var Point = {}
// create an object like this one, but with a clean state
Point.create = function create () {
var 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
}
// we can create objects based off the original Point
var point = Point.create(5, 5)
point.x // 5
point.y // 5
// Or we can create more "Class-like" structures
var 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 tack on to the prototype chain
var square = Shape.create(1, 1, 20, 20)
// what's even cooler, is that since every object inherits the .create() method
// from their "Class" (and the classes are just normal objects anyway) every
// object can act like a "Class"!
var 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
// No More Classes! Just objects!
// Here's what the resulting prototype chain might look like:
//
// Point <- point
// \
// <- Shape <- square <- cube
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment