JS features you better know 1

In scope of functions arguments is local variable provides some nice features we can use in our code. First you don’t need to define any parameters for a function. You can just use arguments and will get arguments passed to the function.

    function sum(){
        var ret = 0;
        for (var i = 0; i < arguments.length; ++i) {
            ret += arguments[i];
        }
        return ret;
    }

    sum(1, 2, 3) //returns 6

Worth noting though that although we use arguments like an array, it’s not an actual javascript Array — it’s just an object. So you can’t do join(), pop(), push(), slice() and so forth.(You can convert it to a real array if you want: “var argArray = Array.prototype.slice.call(arguments);” )

arguments.callee property refers to the function that is currently running. It provides a way for unnamed function to refer to itself. This allows to make nice recursions:

    function fibonacci(){
        if (arguments.length == 1 && arguments[0] > 2) {
            return arguments.callee(arguments[0] - 2, [0, 1]);
        }
        if (arguments[0] == 0) {
            return arguments[1];
        }
        else {
            var len = arguments[1].length;
            return arguments.callee(arguments[0] - 1, arguments[1].concat(arguments[1][len - 1] + arguments[1][len - 2]));
        }
    }
    fibonacci(7) //returns [0, 1, 1, 2, 3, 5, 8]

Notice that “callee” property allows to do recursion with anonymous functions.

arguments.callee.caller property refers to a method called your function. This could be useful for example if you want to forbid public class creating and allow it for Factory only:

    function MyClass(){
        if (arguments.callee.caller != MyFactory.createObject) {
            throw new Error("There is no public constructor for MyClass.");
        }
        this.myproperty = "hello world";
    }
Posted in post | Tagged , | Leave a comment

“Even Faster Websites”

OReily Even Faster Websites is a great book. It has some Javascript perfomance hints in its “Writing Efficient JavaScript” part. Here are conclusions:

  • Use local variables
  • Avoid with statement
  • do not use too deep properies, redefine them with locals if possible
  • Use the if statement when:
    — There are no more than two discrete values for which to test.
    — There are a large number of values that can be easily separated into ranges.
  • Use the switch statement when:
    — There are more than two but fewer than 10 discrete values for which to test.
    — There are no ranges for conditions because the values are nonlinear.
  • Use array lookup when:
    — There are more than 10 values for which to test.
    — The results of the conditions are single values rather than a number of actions
    to be taken.
  • To improve perfomance of loops decrement the iterator toward 0 rather than incrementing toward the total length.
Posted in post | Leave a comment

take control over class constructor

Javascript doesn’t give us simple way to control object constructing. We have new operator, but we cannot control it. Unless we do some magic.
Lets assume we have an observer instance, few classes and we want every instance of this classes to be ‘observed’.

var observer=[]// simplest ever
function foo(){
     this.foo="foo";
     ....
}
function bar(){
     this.bar="bar";
     ....
}

function observe(child){ //MAGIC
	childName=child.name||child.toString().match(/function\s*([^\(])\s*\(/)[1];
	newConst=function(){
	    ret={};
	    child.apply(ret, arguments);
            observer.push(ret);
	    return ret;
	};
	newConst.name=childName;
	window[childName]=newConst;
}

observe(foo);
observe(bar);

var t1=new foo();
var t2=new bar();

observer // t1,t2
Posted in post | Tagged | Leave a comment

javascript constructor with arguments

There was an interesting question on stackoverflow recently. Nobody had right answer. Now after few days i got it! It is really a peace of JS art.
The question was if it is possible to call constructor like this:

someClass(arg1,arg2,...,argN){
.... //implementation
}

having just an Array of arguments [arg1,arg2,...,argN]. First thought was just to use apply. Next was: how can you use apply on a constructor? But it seems you really can:)

var args=[arg1,arg2,...,argN];
var inst={};// this will be instance of our class
someClass.apply(inst,args);// magic here

You see from this point of view javascript constructor is just a method(function) applied to object cloned from its prototype.

Posted in post | Tagged , | Leave a comment

SVG have a great potential.

What intriguing me most of all about SVG is the Adobe. Since SVG is a competitor to Flash. And Adobe was active contributor to SVG and then buys Macromedia in 2005. So I suppose there is a possibility that for Adobe will give up developing of 2 competitive technologies. And I think this won’t be Flash.
But it seems not SVG either.
Since, we have a great JS library – Raphael. It provides solid interface to draw SVG/VML. So we have crossbrowser vector graphics solution now.
Also it seems google will get into it too Google to slip SVG into Internet Explorer (http://code.google.com/p/svgweb/)

Flash is a great technology but it doesn’t give me direct access to all elements of vector graphics elements. So I need some bridges between JavaScript and Actionscript those “almost” similar both ECMAScript languages. That is very sad.

Great to have SVG!

Posted in post | Tagged , | Leave a comment

Google Web perfomance initiative.

Gogle initiates a really great project recently: Let’s make the web faster
So Optimizing JavaScript code article got in scope of my interest.
Conclusions:

  • use [<string>,<string>,<string>].join(“”) for string concatenation (* this is pretty well known rule)
  • use prototype method defining rather than defining method inside closure
  • Creating a closure is significantly slower then creating an inner function without a closure, and much slower than reusing a static function.

By the way – in the last one “significantly” means(lower is better)
for Chrome2: 20:10:1
for FireFox3: 500:50:1
for IE6: 2:2:1
I think this is really significantly:)

Posted in post | Tagged , | Leave a comment

Javascript performance. Array vs Object.

Big JavaScript application needs big storage. JS gives us 2 options Array and Object. I have tested following cases:

  • writing data
  • writing data randomly
  • reading data
  • reading data randomly

I have tested this in following browsers:

  • IE
  • FF
  • Chrome

I want to point out that i am not comparing browsers. I am comparing two methods of storing data in JavaScript.

I have checked perfomance of following pices of code:

writing [ ]

// initialization
var r=[];
//code to evaluate
for (i=0;i<10000;i++){
    this.r[i]=7;
}

writing {}

// initialization
var r={};
//code to evaluate
for (i=0;i<10000;i++){
    this.r[i]=7;
}

writing [ ] randomly

// initialization
var r=[];
//code to evaluate
for (i=0;i<10000;i++){
    this.r[Math.floor(Math.random(1000))]=7;
}

writing { } randomly

// initialization
var r={};
//code to evaluate
for (i=0;i<10000;i++){
    this.r[Math.floor(Math.random(1000))]=7;
}

Here are results in ms:

  IE6 FF3.5 Chrome3
writing [] 14.85 0.95 0.6
writing {} 14.05 4.3 0.65
writing [] randomly 36.7 4.1 1.55
writing {} randomly 37.5 6.15 1.6
reading [] 12 0.2 0.4
reading {} 13.3 1.5 0.35
reading [] randomly 71.05 57.2 53.05
reading {} randomly 71.1 48.9 53.65

Ok the result shows us that the perfomance of Array and Object as storage is almost equal.
So semantically i think it is wise to use array for unordered information and object for mapping.

Posted in post | Tagged , , , | Leave a comment