My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Thursday, May 17, 2007

Joking with JavaScript constructors

This object is Rhino on Cocoon Flow.js Ready (if it's configured to don't use code evaluation using eval), have fun with crazy inheritances and constructors :)
var Instance = {

/*
Description:
creates a new instance of specified constructor using second parameter as constructr arguments.
This is just a New method alias.

Example:
var str = Instance.Create(String, ["Hello World"]);

Arguments:
Function instance constructor
Array constructor arguments or empty array

Returns:
Object new instance of specified constructor
*/
Create:function(){
return this.New.apply(this, arguments);
},

/*
Description:
creates a new instance of last specified constructor and extends them with every precedent constructor, if present.
Each constructor need to have a dedicated array (empty too) to use them as its arguments.

Example:
function String2(){
this.trim = function(){
return this.replace(/^\s+|\s+$/g, "");
};
};
var str = Instance.Extended(String2, [], String, [" Hello World! "]);

Arguments:
Function1 instance constructor
Array1 constructor arguments or empty array

[Function2 optional instance constructor
Array2] constructor arguments or empty array

...

[FunctionN optional instance constructor
ArrayN] constructor arguments or empty array

Returns:
Object new instance of last specified constructor.
Every precedent constructor will be inherited
without prototype (Object will be instance of last constructor).
*/
Extended:function(){
for(var
i = arguments.length - 3,
Instance = this.New(arguments[i + 1], arguments[i + 2]);
i > 1; i -= 2
) arguments[i - 1].apply(Instance, arguments[i]);
if(arguments.length - 2)
arguments[0].apply(Instance, arguments[1]);
return Instance;
},

/*
Description:
Only one difference with Extended: last argument must be an array, used as every constructor arguments.

Example:
var str = Instance.Multiple(String2, String, [" Hello World! "]);

Arguments:
Function1 instance constructor
[Function2] optional instance constructor

...

[FunctionN] optional instance constructor
Array constructor arguments (used with each constructor) or empty array

Returns:
Object new instance of last specified constructor.
Every precedent constructor will be inherited
without prototype (Object will be instance of last constructor).
*/
Multiple:function(){
var j = arguments.length - 1,
i = 0,
Instance = [];
while(i < j)
Instance.push(arguments[i++], arguments[j]);
return this.Extended.apply(this, Instance);
},

/*
Description:
Method used by Create one.
*/
New:function(constructor, arguments){
for(var
i = 0,
j = arguments.length,
Instance = new Array(j);
i < j; i++
) Instance[i] = "arguments[".concat(i, "]");
return new Function("constructor, arguments",
"return new constructor(".concat(Instance.join(","), ")")
)(constructor, arguments);
}
};

No comments: