JS prototype
http://conceptf1.blogspot.co.il/2013/11/javascript-prototype-property-and-Inheritance.html
by Ram Tobolski
JavaScript
//Define a functional object to hold employee in JavaScript
var Employee = function(name) {
this.name = name;
this.number = 3;
};
//Add dynamically to the already defined object a new getter
Employee.prototype.getName = function() {
return this.name;
};
Employee.prototype.getNumber = function() {
return this.number;
};
//Create a new object of type Employee
var judy= new Employee("Judy");
//Try the getter
//alert(judy.getName());
//If now I modify employee, also Judy gets the updates
Employee.prototype.alertMyName = function() {
alert('Hello, my name is ' + this.getName());
};
//Call the new method on john
//judy.alertMyName();
//Create a new object of type Manager by defining its constructor.
// It's not related to Employee for now.
var Manager = function(name) {
this.name = name;
};
//Now I link the objects and to do so, we link the prototype of Manager
//to a new instance of Employee. The prototype is the base that will be
//used to construct all new instances and also, will modify dynamically
//all already constructed objects because in JavaScript objects retain
//a pointer to the prototype
Manager.prototype = new Employee();
//Now I can call the methods of Employee on the Manager, let's try,
//first I need to create a Manager.
var myManager = new Manager('John Smith');
myManager.alertMyName();
//If I add new methods to Employee, they will be added to Manager,
//but if I add new methods to Manager they won't be added
//to Employee. Example:
Employee.prototype.setSalary = function(salary) {
this.Salary = salary;
};
Employee.prototype.getSalary = function() {
return this.Salary;
};
//Let's try:
myManager.setSalary(30000);
alert(myManager.getSalary());
judy.setSalary(60000);
//alert(judy.getSalary());
//Now if I added a property to Manager
Manager.prototype.Projects =function(){
return "Handling multiple projects";
}
//Projects function will be available for managers...