Objects in JS
by Alon Rotem
JavaScript
function Person (fname, lname, myage) {
var age = myage;
this.getAge = function () { return age; }
this.setAge = function (newage) { age = newage; }
this.firstname = fname;
this.lastname = lname;
this.toString = function(){ return this.fullname + ", age: " + age; }
}
Person.prototype = {
get fullname() {
return this.firstname + " " + this.lastname;
},
set fullname(name) {
var names = name.split(" ");
this.firstname = names[0];
this.lastname = names[1];
}
};
function Superhero (fname, lname, myage, power) {
Person.call(this, fname, lname, myage);
this.superpower = power;
this.demonstrateSuperPower = function(){
return "I can " + this.superpower + "!!!";
}
}
Superhero.prototype = new Person();
var superman = new Superhero("Alon", "Rotem", 25, "fly");
alert(superman.lastname);
//alert(superman);
//alert(superman.demonstrateSuperPower());
Date.prototype.GetExactTime = function() {
function pad(str){ str=str.toString(); return ((str.length==1)? ("0" + str) : str);}
var exactTime = "It's exactly "
+ pad(this.getHours()) + ":"
+ pad(this.getMinutes()) + ":"
+ pad(this.getSeconds()) + "."
+ this.getMilliseconds();
return exactTime;
}
//alert(new Date().GetExactTime());