このサンプルは、JavaScriptのPersonクラスにprototypeを利用してメソッドを追加します。prototypeを利用すると複数のインスタンスでメソッドを共有することができますのでメモリを節約できます。
function Person(id, name) {
this.id = id;
this.name = name;
this.age = -1;
this.gender = 'male';
}
// print()メソッド
Person.prototype.print = function() {
return this.id + ', ' + this.name + ', ' + this.age + ', ' + this.gender;
}
// log()メソッド
Person.prototype.log = function() {
if (typeof console != 'undefined') {
console.log(this.print());
} else {
alert(this.print());
}
}