prototype ってなに?

サンプル

[source] [reload]

Prototype の基本的な使い方

// ===============================================
// prototype の基本的な使い方
// ===============================================
function Clock(){
}

Clock.prototype = {
  setDiv : function(id) {
    this.div = document.getElementById(id);
  },
  updateTime : function() {
    var now = new Date();
    this.div.innerHTML =
      now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
  },
  start : function() {
    var _this = this;
    setTimeout( function(){
      _this.updateTime();
      _this.start();
    }, 1000);
  }
}

Prototype は実行時に拡張できる

// ===============================================
// prototype を実行時に拡張する
// ===============================================
function mokeyPatching() {
  Clock.prototype.flag = true;
  Clock.prototype.updateTime = function() {
    var now = new Date();
    
    if( this.flag ) {
      this.div.innerHTML =
        now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
    } else {
      this.div.innerHTML =
        now.getHours() + ' ' + now.getMinutes() + ' ' + now.getSeconds();
    }
    this.flag = !(this.flag);
  }
}

Prototype を使ったクラスの継承

// ===============================================
// prototype を継承する
// ===============================================
function RotateClock() {
}

RotateClock.prototype = new Clock();
RotateClock.prototype.location = 0;
RotateClock.prototype.updateTime = function() {
  var now = new Date();
  var timeString = 
    '        ' + 
    now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
  
  var end = this.location + 8;
  end = end > timeString.length ? timeString.length : end;
  
  this.div.innerHTML = timeString.substring(this.location, end);
  
  this.location = (this.location + 1) % 16;
}

Prototype で定義した属性か?それともオブジェクトの持ち物か?


HTML


添付ファイル: fileprototype.html 3197件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS   sitemap
Last-modified: 2011-02-21 (月) 01:30:46 (4805d)
Short-URL: https://at-sushi.com:443/pukiwiki/index.php?cmd=s&k=78ce303808
ISBN10
ISBN13
9784061426061