Skip to content

Instantly share code, notes, and snippets.

@tangrammer
Created December 23, 2012 20:59
Show Gist options
  • Save tangrammer/4366082 to your computer and use it in GitHub Desktop.
Save tangrammer/4366082 to your computer and use it in GitHub Desktop.
Prototypal Inheritance implemented in Person and PersonLocalized functions. Use core.js and i18n.js to use "init, getters" and "date_printer, wage_printer" respectively. date_printer and wage_printer are outside PersonLocalized function for better reuse. Both use closure to acces the data values
// this file use ./core.js and ./i18n.js
var data_person_example={
id: 1,
fname: "Juan Antonio",
lname: "Ruz",
DOB: "1976-06-13",
wage: 100,
};
function Person(){
getters(this, ["id", "fname", "lname", "DOB", "wage", "location"]);
};
function create_person(spec){
var p=new Person();
init(p, spec);
// converting p.DOB from string value to date value
p.DOB=new Date(p.DOB);
return p;
}
function PersonLocalized(){
this.get_fname=function(){return "i18n_ "+this.fname};
this.get_DOB=function(){
return date_printer[this.lang].call({date:this.DOB});
};
this.get_wage=function(){
return wage_printer[this.lang].call(this);
};
};
PersonLocalized.prototype=new Person();
PersonLocalized.prototype.lang="US";
function set_locale(new_lang){
PersonLocalized.prototype.lang=new_lang;
};
function internationalize(person){
var p_l=new PersonLocalized();
init(p_l, person);
return p_l;
};
function invoke_i18n_methods(_p){
log("\nDebug Person:\nLanguage: "+(_p.lang || "NO LOCALIZED"));
log(_p.get_fname());
log(_p.get_DOB());
log(_p.get_wage());
}
var person=create_person(data_person_example);
var person_i18n=internationalize(person);
var other_person=create_person({id: 5, DOB: "1999-07-23", wage:150, fname: "PEPE"});
var person_i18n_bis=internationalize(other_person);
invoke_i18n_methods(person);
/*
Debug Person:
Language: NO LOCALIZED
Juan Antonio
Sun Jun 13 1976 02:00:00 GMT+0200 (CEST)
100
*/
invoke_i18n_methods(person_i18n);
/*
Debug Person:
Language: US
i18n_ Juan Antonio
US: 06/13/76
US: $100
*/
set_locale("AU");
invoke_i18n_methods(person_i18n);
/*
Debug Person:
Language: AU
i18n_ Juan Antonio
AU: 13/06/76
AU: $100
*/
invoke_i18n_methods(person_i18n_bis);
/*
Debug Person:
Language: AU
i18n_ PEPE
AU: 23/07/99
AU: $150
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment