このサンプルは、JavaScriptのPersonクラスにprint()とlog()のメソッドを追加します。print()メソッドは、Personクラスのid, name, age, genderプロパティを取得して返します。log()メソッドは、console.log()またはalert()関数でPersonのプロパティを表示します。
function Person(id, name) {
this.id = id;
this.name = name;
this.age = -1;
this.gender = 'male';
// print()メソッド
this.print = function() {
return this.id + ', ' + this.name + ', ' + this.age + ', ' + this.gender;
}
// log()メソッド
this.log = function() {
if (typeof console != 'undefined') {
console.log(this.print());
} else {
alert(this.print());
}
}
}