JavaScript doesn't have any class structure. but you can use constructor functions as classes.creating a constructor function is simple (just like creating a normal function). and you can have public members, private members, static members, privileged members(it is a way to access private members of your constructor).
//simple constructor function
function Employee(){
//private property
var name = "default Employee";
//private function
function setDefaultSalary(){
return 5000;
}
//public property
this.defaultCommision = 300;
//privilaged method
this.displayEmployeeInfo = function(){
alert(name + " Salary: " + (this.defaultCommision + setDefaultSalary()));
}
}
you done with constructor function. now it's time to play with Objects. creating a object of Employee type is easy. JS provided a new Operator for this.
//Object creation based on your Constructor
var myEmployee = new Employee();
//you can't acess private members
alert(myEmployee.name)// undefined
//you can acess public memebers
alert(myEmployee.defaultCommision);//300
//privilaged method
myEmployee.displayEmployeeInfo();
before going to dig more on the Object Oriented features in JavaScript remember that for JS developers functions are objects... blindly remember objects hold properties and methods.
No comments:
Post a Comment