Shape-Shifting in Javascript

Mixology is a Ruby library for what I call shape-shifting objects. 

shape·shifting

n. the act of changing the shape of an object's inheritance hierarchy during runtime.

It turns out that shape-shifting is incredibly easy to do in Javascript.
ClosedDoor = {
  isClosed: function(){
    return true
  },
  isOpen: function(){
    return false
  }
}

OpenDoor = {
  isClosed: function(){
    return false
  },
  isOpen: function(){
    return true
  }
}

function Door(){
  this.__proto__ = ClosedDoor
  this.open = function(){
    this.__proto__ = OpenDoor
  }
  this.close = function(){
    this.__proto__ = ClosedDoor
  }
}
Let's give it a go:
> door = new Door()
Object
> door.isClosed()
true
> door.isOpen()
false
> door.open()
> door.isOpen()
true
> door.isClosed()
false
In Javascript, "inheritance" is nothing but a link from the child to the parent: the __proto__ property. Once you have this link established, the child inherits all of the properties of the parent. You can change the __proto__ property at runtime. What the example did is simply to change the parent of the door instance to a ClosedDoor or an OpenDoor whenever the state of the door changes. This make for a nice way to implement states. +2 points for prototype inheritance!

Update: caution, this code - in particular the __proto__ attribute, will not work in IE and is also deprecated in Mozilla.

blog comments powered by Disqus