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

Monday, December 31, 2007

[OT] Never forget old school!

Another year has gone, new technologies are coming but please never forget genuine old style. Happy new year to everyone from me and old "friend" :D

Saturday, December 29, 2007

Is JSON forgetting something?

I played many times with JSON serialized data, creating odd alternatives too like JSTONE or JSOMON.

Few years ago I created even a PHP compatible serializzation but nowadays, with PHP5, json_encode and json_decode are natively integrated in PHP language and, at the same time, even faster than old serialize and unserialize global functions.

The big difference between JSON and PHP serializzation

Both JSON and PHP Serialized data have the same goal: transport objects and data over http protocol or storage these informations inside a cookie, a database or why not, a file.
However, PHP serialize and unserialize functions do more things than JSON serializzation, adding charset/indexes informations transporting even private or protected parameters.

With JavaScript 3rd edition We have not latter kind of properties so we shouldn't care about this limit during serializzation.

This is probably the most important difference between these two different serializzation but there is another one that should be easily implemented in JavaScript too: magic __sleep and __wakeup methods.

What do we need

The most important information we need to make JSON more magic than ever should be the constructor name. Without this information every kind of instance will lose its special methods/properties reducing them as a common Object.
Usually, this is exactely what we would like to transport, keys and values or, in the case of Array, only its values.
I'm thinking about something like that:

function A(){};
function B(){};
B.prototype.__wakeup = function(){
this.d = String.fromCharCode(this.c + this.a.charCodeAt(0));

var a = new A;
a.a = "b";
a.c = "d";
a.e = new B;
a.e.a = "b";
a.e.c = 3;

// $("A",{"a":"b","c":"d","e":$("B",{"a":"b","c":3})})

I think that original objects doesn't need their constructor name.
In this way the unique change is for different instances and JSON syntax is quite the same.

With a string like that we should use eval too in a simple way:

function decode(str){
function $(constructor, o){
var result = eval("new ".concat(constructor)), key;
for(key in o){
result[key] = o[key];
if(typeof result.__wakeup === "function")
return result;
return eval(str);

function A(){};
function B(){};
B.prototype.__wakeup = function(){
this.d = String.fromCharCode(this.c + this.a.charCodeAt(0));

var o = decode('$("A",{"a":"b","c":"d","e":$("B",{"a":"b","c":3})})');

alert([o instanceof A, o.e instanceof B, o.e.d]);

The __wakeup magic method should be used to do something before the object will be assigned, extremely useful in a lot of common situations.

What about __sleep?

The magic __sleep method should be the same used with PHP.
A simple prototype that could do everything but that needs to return properties we want to serialize.

This should be a JSON parser problem that could check every instance and use, only if it's present, its __sleep method.


  • constructor name for instances that are not just objects

  • better server side parsers to manage instances without loosing their constructor name

  • a global name for dollar function, if some library use them as constructor too to avoid problems during instance creation (or a simple global-scope evaluation for each new "constructor" assignment)

This is just a personal brainstorming/proposal and I would like to know what do you think about that.

P.S. marry Christmas and happy new year :-)

Friday, December 21, 2007

JavaScript Iterator for IE and other browsers

This is just my proposal to add Iterator in Internet Explorer and other browsers too.


function Iterator(obj, name){
// Iterator(obj) and new Iterator(obj) behaviour
if(this instanceof Iterator){
var i = 0,
result = [],
skip = false,
for(key in obj){
result[i++] = name ? key : [key, obj[key]];
this[key] = undefined;
if(!skip && (key == "constructor" || key == "toString" || key == "valueOf"))
skip = true;

// solve IE problems
for(var l = 0, arr = ["constructor", "toString", "valueOf"]; !skip && obj.hasOwnProperty && l < arr.length; l++){
result[i++] = name ? arr[l] : [arr[l], obj[arr[l]]];
this[arr[l]] = undefined;

// add next method if any next in object = function(){
if(i === result.length)
throw new StopIteration;
return result[i++];

// reset result "pointer"
i = 0;
return new Iterator(obj, !!name);

function StopIteration(message, fileName, lineNumber){
this.message = message;
this.fileName = fileName;
this.lineNumber = lineNumber;
StopIteration.prototype = new Error;

// global scope check
this.Iterator = Iterator;
this.StopIteration = StopIteration;

// test it!
var iter = Iterator({a:"b", next:"c", toString:"hello"}),
output = [];
if(err instanceof StopIteration)
output.push("End of record");
output.push("Unknown error: " + err.description);

The best way to use them is with method but you could use a for in loop too.
However, in latter case if the object has a next property, it will be overwrote by dynamic method but this problem apart, enjoy iterators :-)

Thursday, December 20, 2007 ... again online

I am sorry for last days while wasn't working as expected because of new server.
It seems to be faster than precedent one so thank you again Daniele , I'll write your link as soon as I can :-)

Enjoy both JavaScript and CSS compressed files in a single one, enjoy!

Monday, December 10, 2007

FireFox, Safari, and Opera ... JavaScript Conditional Comment

I've still written a comment in John Resig blog about Re-Securing JSON and FireFox or Safari 3 const behaviour to create an immutable function, called Native, and to retrieve original Array, Object, String or other constructors.

This is the function:

const Native = (function(){
const NArray = Array,
NBoolean = Boolean,
NDate = Date,
NError = Error,
NMath = Math,
NNumber = Number,
NObject = Object,
NRegExp = RegExp,
NString = String;
return function(Native){
case Array:return NArray;
case Boolean:return NBoolean;
case Date:return NDate;
case Error:return NError;
case Math:return NMath;
case Number:return NNumber;
case Object:return NObject;
case RegExp:return NRegExp;
case String:return NString;

// Example
Array = Native(Array);

At the same time I've talked about IE behaviour and its missed support for const.

While I was thinking about that I imagined a way to use a piece of code, in this case the keyword const, compatible with every browser.

It should sounds simple, just use the well know trick IE=/*@cc_on ! @*/false; followed by if(IE) ... but ... hey, I need everytime to create a double version of the "same script" ... is it good?

Try to imagine a variable that should be a constant for every compatible browser but at the same time should be declared just one time ...

const MyConstant = 1;

With every day practices we should use a try catch or some strange trick to evaluate a const declaration ... don't we?

But we have a particular behaviour of the conditional comment ... it should contains a comment itself too, sounds cool?

/*@cc_on // @*/ const
Native = function(){
// whatever You need

Can anyone trigger an error with above piece of code? :-)

In this way FireFox 2+, Safari 3+ (I don't know about 2), and Opera 9+ could work without problems disabling Native variable re-declaration while every IE browser will ignore the const keyword.

I suppose this trick is not so new but never as this time it should be useful to make code more slim and efficient.

Instant Update
The usage of const inside the private scope of Native function declaration is not so useful (just a little bit of paranoia :D) but in these cases we could use a better trick to create local variables with internet explorer too.

This is an example:

Native = (function(){
/*@cc_on var // @*/ const
NArray = Array,
NBoolean = Boolean;
return function(Native){
return Native === Array ? Narray : NBoolean;

Above example shows how should be possible to initializzate multiple variables using a comma and respecting the private scope.
Internet Explorer will use var while every other browser will try to use const if it's compatible.

Sounds even better? I hope so :-)

P.S. Native function is quite interesting, imho, that's why I choosed to add them in

Wednesday, December 05, 2007

Looking for a job in London ... or not?

It's about 2 weeks that I'm studying in London to improve my English knowledge, specially my spoken one (I know, written is not so perfect too).

I put my cv on line in a famous recluting search engine but it seems that most interested people are Agency's employees that usually look for generic IT - Web masters.

I would like to explain my "strange situation": I am not absolutely a web designer, I do know quite nothing about graphic, I could just know how to start Gimp!!! :D

It seems that if You know quite perfectly ActionScript 1.0/2.0, that's basically ECMAScript 3rd edition or, in case of 2.0, 4th one closed, you can be only a Web Designer and not a programmer, even if You know Flash Player bugs and you're able to find out workarounds.

It seems that if You know deeply JavaScript (best practices, OOP, Ajax, cross-browser/platform development, bugs, common libraries suggestions) it's not important ... just a preferred plus ... but at the same time everybody is looking for Ajax and Web 2.0 skilled developers, a role that absolutely requires a good programming background (not just a bit of DreamWeaver).

It seems that if you know different languages or technologies ... there's always a missed one.
How can a person to be "senior in every program language"?
I can't call their "expert or senior everything developers", a part for someone who has at least 20 years or more experience.

However, excellent OO PHP 4/5,JavaScript,ActionScript,(x)HTML,CSS,XML skills aren't enough while a good knowledge of C# for ASP.NET or MONO, and Python is not enough as a technical plus.

Maybe someone should be interested in my good database skills, starting from SQLite 2/3 to MySQL 3/4/5, passing inside PostgresSQL ... but it's not enough.

What about security practices and code optimization skills? Who cares about that!

As sum, and as someone said before me: please hire me !!! :-)

Best regards,
Andrea Giammarchi