Skip navigation

Monthly Archives: June 2012

this is powerful but at the same time if used without care it is dangerous too. Consider the example snippet below

// define Human class
var Human = function(name) { = name;
    this.say = function(){
        return "I am " +;
var author = new Human('raja');
var badAuthor = Human('ford');  // new keyword missing

alert(typeof author); // object
alert(typeof badAuthor); // undefined because context changed to window
alert(  // raja
alert(  // ford

Notice how missing new keyword changing the context to window object.

Play with it.


While surfing through internet I came across one interesting JavaScript technic. Just observe the code snippet below

// self redefining function
var myFunction = function () {
    //set up code only to this once
    alert("set up, only called once");

    // set up code now complete.
    // redefine function so that set up code is not re-executed
    myFunction = function() {
        alert("no set up code");
myFunction(); // outputs - Set up, only called once
myFunction(); // outputs - no set up code this time
myFunction(); // outputs - no set up code this time 

In practical scenario we can use it intelligently. What do you say??? 🙂