[僕] prototype でメソッド追加

僕ト云フ事

たろマークはてなブックマーク

2007年09月22日

[javascript][prototype] prototype でメソッド追加

prototype で以下のようにやると this には Hoge のオブジェクトが渡ってくる。

function Hoge (x, y) {
    this.x = x;
    this.y = y;
}
Hoge.prototype.test = function () {
    alert( this.x );
}
 
var hoge = new Hoge(2, 5);
hoge.test(); // 2

例えば、Array で特定の要素を削除するメソッドを追加したい時はこんな感じでメソッドを追加できる。

Array.prototype.remove = function (k) {
    var newary = [];
    var j = 0;
    for ( var i = 0; i < this.length; i++ ) {
        if ( i != k ) {
            this[j] = this[i];
            j++;
        }
    }
    this.length = this.length - 1;
}
 
var ary = ['hoge', 'foo', 'bar'];
ary.remove(1);
alert( ary ); // hoge, bar

ちなみに古いブラウザに対応するのでなければ、上記の例は splice を使えばいいらしい。

ary.splice(1, 1);
blog comments powered by Disqus