Thursday, January 6, 2011

Some Javascript basics

I used javascript for many years, did many things that solved hard problems at work. However I recently changed work, and this company used javascript heavily.

Through my recent debugging and fixing of the code, I found some old javascript tricks that I never know!!

1. === and !==. "===", the triple equal sign, means compare with type. So even though 2=="2" is true, 2 === "2" is false because their types are different. Same with !==. I found this one while I was reading jQuery code.

2. function closures.
(function(){
//do something without affect globals.
})();

2. call and apply.
Suppose you have a function doSomething(a,b). You can call itwith a new "this" by using call and apply. i.e

3. arguments
It is a variable made available by javascript that contains current function call's arguments.

function doSomething(a,b){
alert(this.id + ' ' + a + b);
}
var obj = {id:'me'};
var func = doSomething;
func.call(obj, 1, 2);
(function(){func.apply(obj, arguments);})(1,2);

the above code will show "me 12" twice.

Because I never know those before, the first time I saw them, I thought they are either typos or some home made functions!!

No comments: