Tuesday, February 19, 2008

Javascript equivalent of perl attributes.

This javascript enabled page contains code for this article
It was checked under Mozilla Firefox 2.0.0.12


In one of my previous posts I have considered perl attributes.

Attributes are functions itself,that could be defined by user, and that have access to another function body, and can operate another functions, at the moment of definition of the functions with the attributes.

For example, when such definition met by Perl in the Perl script,

sub func_sub : attribute_func 
Perl executes attribute_func, passing func_sub to the function. Then attribute_func can change func_sub executable body, adding "header" and "footer" to the function, or alerting about definition met, for example.

Due to the fact, that JavaScript is also used widely for web applications, but on client side,
I have asked myself about equivalent JavaScript form.

It appeared, that for JavaScript it is even more simple equivalent exists, that can be used for understanding Perl attributes definition. Attribute can be implemented as high order function, that manipulates function body.

We can log function in and out using following attribute function defined as following closure:

function attr (fparam){
document.writeln("attr.beginning< br >");
fparam();
document.writeln("attr.end< br >");
}

Example of how it can be applied:

a = function(var_my)
{
attr(function()
{
document.writeln("this is first line of original function (a) < br >");
document.writeln("var passed:" + var_my + "< br >");
} )
};

document.writeln("perform call to a() < br >");
a("1");

More complex example of attribute , that modifies code of function
before function will be executed:

We define attribute that prints function's code given, and that adds additional strings of code to function, and define this new function under the different name, and than executes modified function.

It is example of self-modifying code.


// prints a lot of debug info,
// define new function like given, but with changes in body
// and execute it.
function attr2 (fparam){
document.writeln("attr.beginning < br >");
document.writeln("func get:" + fparam +"< br >");
var tempstr = new String;
tempstr = fparam.toString();
tempstr = tempstr.replace(");","); global_var*=2;
document.writeln(\"inserted by attr2\");" );
tempstr = tempstr.replace("function ()",
"function b_modified()");
var func = tempstr;
document.writeln("Now call func made by attr2:"
+ tempstr + "< br >");
eval(func);
b_modified();
document.writeln("attr.end< br >");
}

// define b as attr2(anonimous function given)
b = function()
{
attr2(function()
{
document.writeln("this is first line of original function (b)< br >");
document.writeln("global_var="+ global_var);
} )
};

// global_var is printed and modified inside b
var global_var=2;
b();



In the begining of article link to the place were all the code cited
can be viewed in action published.

No comments: