Edited at

JavaScriptのクラス書き方(テンプレート )

More than 5 years have passed since last update.

よく忘れるのでメモ。


example.js


(function(){

var Animal;
Animal = (function(){

// private method
var getDistance = function(speed){
return speed * 60;
};

//class変数
Animal.JapaneseName = "動物";

//class method
Animal.called = function(a){
console.log(a + " called.");
};

//constructor
function Animal(name){
//private
this.name = name;
this.data = {
weight:1
}
}

//setter
Animal.prototype.setName = function(name){
this.name = name;
};

//getter
Animal.prototype.getName = function(){
return this.name;
};

//public method
Animal.prototype.move = function(speed){
console.log(this.name + " moved " + getDistance(speed) + " m/h.");
};

/* この書き方でも可
Animal.prototype = {
getRow: function(){
},
setRow: function(r){
}
};
*/

return Animal;
})();

//呼び出し
console.log(Animal.JapaneseName);
Animal.called("bird");

var a = new Animal("dog");
console.log(a.getName());
a.setName("wolf");
console.log(a.getName());
var a2 = new Animal("cat");

console.log(a.data.weight);

a.data.weight = 10;
console.log(a.data.weight);

a2.data.weight = 5;
console.log(a2.data.weight);

a.move(30); // 600 m/h
a2.move(10); // 1800 m/h

})();