Thursday, December 20, 2012

OOPS with JS - Part 2

in the first part i covered few points about encapsulation and creating constructor methods. now it's time to dig more.

for novices: in JavaScript we can create the objects with new operator and with object literal .

//with new operator
var myObject = new Object()// creates an empty object;
var myEmployee = new Employee() // creates an Employee object;

//with object literal notation
var myObject = {} // creates an empty object;
var myEmployee = {name:"srinivas"} //created object with name property.

we will use . operator to access the properties and methods on an object.
alert(myEmployee.name) //srinivas

now it's time to create a base class / parent class.(as usual we need to create a function nothing more else).

function Parent(){
this.whoAmI = "parent";
}
we created a function called Parent. remember JavaScript functions are objects. also remember objects may have properties and methods. so our Patent function also an object (don't be scared just imagine every thing is an object). Parent function is having some methods and properties. let's check some important properties and methods.

Properties
  1. constructor
  2. arguments // deprecated
  3. arity
  4. length
  5. name
Methods
  1. apply
  2. call
  3. toString
some more browser, JavaScript engine specific functions also available. but above are most important. i will discuss each of them when ever they required. apart form these, there is one  more rule of thumb : in JavaScript every object have a property called prototype. that holds an object.

//createing a object
var myParent = new Parent();

//whoAmI is called as object's own property
alert(myparent.whoAmI)//parent

//our parent function also an object so we will have a prototype property for this.
alert(typeof(Parent.prototype))//object

No comments:

Post a Comment