Tuesday, 7 August 2012

JS-OOP and event handling

OOP:
    In Javascript everything you can manipulate are objects. They include all the Strings, Numbers, Arrays, functions and Objects.

    var x="prem"
    prem.length

    here x is an object which has value as "prem" and property as length.
    We can also create objects such as
    var prem = Object.create(null);

    Here the prem is an object. But where is the class...????
    There is no class, just objects.
    Here we need to think apart from the traditional OOPS where you need to create classes and instantiate the objects using the classes as in java and c#.

  To add the properties

    There are options to allow the get and set methods in the JS. They can be set by using the following syntax,

// () → String // Returns the full name of object. 
function get_full_name() 
{ return this.first_name + ' ' + this.last_name }  
// (new_name:String) → undefined 
// Sets the name components of the object, from a full name. 
function set_full_name(new_name)
 { 
    var names names = new_name.trim().split(/\s+/) 
    this.first_name = names[⁣'0'] || ''  
    this.last_name = names['1'] || '' 
  } 

Object.defineProperty(prem, 'name', { get: get_full_name , set: set_full_name , configurable: true , enumerable: true })


In the above example there is a property called "name". 

prem.name="prem anandh" // set_full_name is called
now,
prem.first_name is "prem"
and
prem.first_name is "anandh"
and of-course,
prem.name //get_full_name is called

Do Classes even exist in JS...?
        Yes. They do. But slightly different from the rest of the languages in which they are used. The syntax is,
       function name( some_variable )
       {
             this.val=some_variable;
        }
       


   

No comments:

Post a Comment