LoginSignup
43
42

More than 5 years have passed since last update.

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

Last updated at Posted at 2013-01-15

よく忘れるのでメモ。

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

})();


43
42
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
42