Skip to main content


Showing posts from September, 2011

JavaScript: Context or Scope

Scope is very confusing specially when we are working on big application. But it's a very useful feature.

When function is the part of the object

var obj = { isUsed: false, use: function(){ this.isUsed = true; } }; -> obj.use(); -> obj.isUsed; //ans: true

What is the context or scope
Context or Scope is the boundary where your code executes.

var x = 10; function test(){ x = 20; //updated the global vlaue } -> alert(x); //ans: 10 -> test(); -> alert(x); //ans: 20
When 'x' is local variable !!!

var x = 10; function test(){ var x = 20; //now x is a local variable of test function } -> alert(x); //ans: 10 -> test(); -> alert(x); //ans: 20

We can change the scope of the function while calling it

function fn(){ this.myProperty = 'test'; } -> fn(); -> this.myProperty; //ans: test -> window.myProperty: //ans: test -> myProperty; //ans: test
When you run the function 'fn' it will run in global scope and set the propert…

JavaScript: Variable type or Object type

In any language it's important and useful to know object type you are dealing with. Here are few ways to identify the object type in java-script

var myVar = {}; var myArr = [0,1]; var myStr = ""; var myNum = 1; var myFloat = 1.2; var myBool = true; var myRegx = /abc/; var myClassObj = new function Neeraj(){};

This is widely use method to identify the object type
Some well known JS Lib. (ie. jquery, extjs etc.. ) use this technique
By Using Object.prototype.toString
Object.prototype.toString.apply(myVar); //ans: [object Object] Object.prototype.toString.apply(myArr); //ans: [object Array] Object.prototype.toString.apply(myStr); //ans: [object String] Object.prototype.toString.apply(myNum); //ans: [object Number] Object.prototype.toString.apply(myFloat); //ans: [object Number] Object.prototype.toString.apply(myBool); //ans: [object Boolean] Object.prototype.toString.apply(myRegx); //ans: [object RegExp] Object.prototype.toString.apply(myClassObj);//ans: [objec…

javascript: functions

Creating a function
function isNimble(){ return true; } var canFly = function(){ return true; }; window.isDeadly = function(){ return true; };
function call by itself
function hello(n){ return n>0? hello(n-1)+"a":"hiy"; }
if you don't want to give function name
function hello(n){ return n>0?arguments.callee(n-1)+"a":"hiy"; }
Named Functions
function hello(){return "hiyaa";} //what is the name of the function ? var emp = function myEmp(){return "emp";}; Functions as Objects
//Normal JavaScript Object var obj = {}; //Simple function declarication var fn = function(){}; //both has properties obj.prop = "some value"; fn.prop = "some value"; //other existing properties in function -> length, call, apply
//without cache function isPrime( num ) { var prime = num != 1; // Everything but 1 can be prime for ( var i = 2; i < num; i++ ) { if ( nu…