Javascript Prototype Pattern
var TaxCalculator = function(data){
this.name = data.Name;
this.basic = data.Basic;
this.allowances = data.Allowances;
this.deductions = data.Deductions;
this.result = 0
}
TaxCalculator.prototype = {
CalculateTax: function(){
this.result = ((this.basic +this.allowances) - this.deductions)*0.1;
}
}
$(document).ready(function(){
var data = {Name:Alex, Basic:4000, Allowances:600, Deductions: 400};
var calc = new TaxCalculator(data);
calc.CalculateTax();
alert(calc.result);
});
Overridding a function in prototype pattern
TaxCalculator.prototype.CalculateTax = function(){
this.result = ((this.basic +this.allowances) - this.deductions)*0.2;
}
Namespaces in javascript
myNamespace = myNamespace || {};
myNamespace.TaxCalculator = function(data){
this.name = data.Name;
this.basic = data.Basic;
this.allowances = data.Allowances;
this.deductions = data.Deductions;
this.result = 0
}
myNamespace.TaxCalculator.prototype = {
CalculateTax: function(){
this.result = ((this.basic +this.allowances) - this.deductions)*0.1;
}
}
$(document).ready(function(){
var data = {Name:Alex, Basic:4000, Allowances:600, Deductions: 400};
var calc = new myNamespace.TaxCalculator(data);
calc.CalculateTax();
alert(calc.result);
});
Module Pattern
var TaxCalculator = function(data){
//private members
var name = data.Name;
var basic = data.Basic;
var allowances = data.Allowances;
var deductions = data.Deductions;
var result = 0;
return {
//public members
CalculateTax : function(){
result = ((basic + allowances) - deductions)*0.1;
return result;
}
};
}
$(document).ready(function(){
var data = {Name:Alex, Basic:4000, Allowances:600, Deductions: 400};
var calc = new myNamespace.TaxCalculator(data);
alert(calc.CalculateTax());
});
No comments:
Post a Comment