Sunday, July 22, 2012

JavaScript Tips and Tricks -4

JavaScript Objects -
Javascript objects are dictionary. In C# you will find objects as an instance of class, but in Javascript every object is actually a dictionary.
var testObject = {};
 is equivalent to
var testObject = new Object();
We can set any property to JavaScript object using "." operator or "[]" operator. Here is the code snippet -

  var testObj = {};
  var testObj1 = new Object();
  testObj.myObj = '1';
  testObj1.myObj = '1';
  testObj["myObj1"] = '2';
  testObj1["myObj1"] = '2';

alert("testObj.myObj--" + testObj.myObj); // alert -1
alert("testObj1.myObj--" + testObj1.myObj); // alert - 1
alert("testObj[myObj1]--" + testObj.myObj1); // alert -2
alert("testObj1[myObj1]--" + testObj1.myObj1); // alert -2


In the above code testObj.myObj and testObj1.myObj are same and can be accessed by "." operator or "[]" operator.

JavaScript Functions-
JavaScript functions are objects with executable code associated with it. Here are 3 different ways of defining same function -
1)
    function test1(x){
    alert(x);}
    test1('myName');
2)
    var func = function(x){
    alert(x);}
    func('myName');
3)
    var func = new Function("x" ,"alert(x);");
    func('myName');
This shows functions are actually objects which supports a function call operation. The following examples shows we can add properties also to the function -
function test1(x){
    alert(x);
    }
    test1('myName');

    test1.text = "myText";
    test1['text1'] = "Another Text";

    alert(test1["text"]);
    alert(test1["text1"]);
    alert(test1.text);
    alert(test1.text1);
It will alert "myText" "Another Text" "myText" "Another Text".

Its possible to pass a function as an argument to another function -
     function square(x){
    return x*x;
    }   
    function operateOnFunc(x, func){
        return func(x);
    }   
    alert(operateOnFunc(4,square)); // alerts 16

Function can be returned as a value from another function -
 function makeSquare(){
    return function (x){ return x * x ;};
 }
 var ans = makeSquare();
 alert(ans(7)); // alerts 49

Constructor function -
In Javascript there is no class/structs. If we want to define any object of our custom type, we use functions. Consider following example -
function MyClass(name){
this.name = name;
    this.respondTo = function (name){
    alert("Hi " + this.name );
    }
}var myObj = new MyClass('class1');

what "new" operator does is, it creates new empty object and execute the function on that empty object. In other word new operator is equivalent to -
var myObj = {};
MyClass.call(myObj, 'class1');

Prototype -
The prototype object is a central concept in object oriented programming with JavaScript. Every properties and methods of prototype object will appear as properties and methods of the object created from prototype constructor. In JavaScript every function has property named as "prototype" that refers to prototype object and this prototype object has property named as "constructor" which refers to this object back.
Lets consider a Dog class to understand different scenario of prototype-
function Dog(name){
this.name = name;
    this.respondTo = function (name){
    alert("Hi " + this.name );
    }
}
 var spot = new Dog("Spot");
 alert(Dog.prototype.isPrototypeOf(spot)); // true
 alert( spot.constructor == Dog.prototype.constructor); // true
 alert( spot.constructor == Dog); // true

The constructor property belong to prototype not to original object.
alert(spot.hasOwnProperty("constructor")); // false
alert(Dog.prototype.hasOwnProperty("constructor"));//true
Note - you wont find prototype method on spot, you will find it on Dog.
Every new instance of Dog will share the same prototype object.

Even if objects share the same prototype object then also making change in prototype by one object wont reflect on other. Here is the example -
 function GreatDane(){};
var rover  = new GreatDane();
var spot = new GreatDane();

GreatDane.prototype.getBread = function (){
     alert( "Dane");
}
spot.getBread(); //Dane
rover.getBread(); //Dane

//hides getbread in greatDane.prototype
spot.getBread = function (){
alert( "spot");
}
spot.getBread(); //spot
rover.getBread(); //Dane
Changes to getBread never propagate to prototype.

Every JavaScript object inherits chain of prototypes, all of which ends with Object.prototype. Object.prototype is ultimate prototype for all prototypes in JavaScript. The prototype of Object.prototype is null.
Here is the flow which gives insight of how toString() method get resolved in JavaScript -

Static Properties-
Static fields are bound to class not to instance of the class. Creating static properties in JavaScript is easy as functions are objects whose properties can be set on desire. Since constructor function represent a class in JavaScript you can add static properties of that class simply by setting to constructor of that class. Here is the example -
function myFunc(){}
    myFunc.myStatic = function() {
        return "Hi";
    }
alert(myFunc.myStatic());

Reference - http://msdn.microsoft.com/en-us/magazine/cc163419.aspx

No comments:

Post a Comment