Skip to content

Instantly share code, notes, and snippets.

@purplecabbage
Created March 6, 2011 21:23
Show Gist options
  • Save purplecabbage/857685 to your computer and use it in GitHub Desktop.
Save purplecabbage/857685 to your computer and use it in GitHub Desktop.
adding namespaces to the prototype chain in js.
var Class = {};
Class.namespace = function(ns,value)
{
var nsArr = ns.split(".");
var obj = window;
var prop;
for(var n=0; n < nsArr.length-1; n++)
{
prop = nsArr[n];
if(!obj[prop])
{
obj[prop] = {};
}
obj = obj[prop];
}
obj[nsArr[nsArr.length-1]] = value;
return obj;
}
Class.extend = function(_super, proto)
{
this.prototype = new _super();
if (proto)
{
Class.mixin(this.prototype,proto);
}
return this.prototype;
};
Class.mixin = function(obj,proto)
{
for (var i in proto)
{
obj[i] = proto[i];
}
};
// Sample Use
var DuckObj = function(){};
DuckObj.prototype.quack = function()
{
console.log("I am a duck!");
}
Class.namespace("some.sort.of.hybrid",
Class.extend( DuckObj,
{
bark:function()
{
console.log("I am a dog");
}
}));
some.sort.of.hybrid.bark();
some.sort.of.hybrid.quack();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment