Saturday, February 28, 2009

A neat pattern

This neat javascript pattern just came to my mind. Consider this class constructor:

var Base = function(o) {
  for (var i in o) this[i] = o[i];

Pretty basic constructor, right? This class can have a prototype and we can subclass it like so:

Base.prototype = {a : 1};
var Sub = new Base({b : 2});
var sub = new Sub();
sub.a == 1; //true
sub.b == 2; //true

It just occurred to me that since a constructor is a function, it can also be call()'ed, like so:

var A = function() {};
A.prototype = {a : 1};

var B = function() {};
B.prototype = {b : 2};, A.prototype); //class B extends class A

var a = new A();
var b = new B();, a); //instance b extends instance A, A.prototype); //instance b extends class A, A); //static B extends static A

I've seen the extend() pattern pretty much everywhere but I haven't come across anything that uses this same Base function as a class constructor as well as an general purpose "extend()" / "clone()". I wonder if anyone uses it like this.

No comments:

Post a Comment