Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

prototypeを使うと既存オブジェクトを拡張可能

prototypeは既存オブジェクトに手を加えるメソッドです。

実際のところ

オブジェクト指向的な書き方をした、以下の様な関数があったとします。

function Person(fist, last) {
 this.first = fist;
 this.last = last;
}

p = new Person('gogo', 'yubari')

このままだと、当然メソッドはありません

p.fullName()
// undefined

ここで、prototype経由でメソッドを設定してから読むと……ちゃんと動きます。

Person.prototype.fullName = function() { return this.first + " " + this.last }

console.log(p.fullName())
//=> "gogo yubari"

更に……なんと既存のオブジェクトに対する上書き拡張すら可能となっています。
わぁ何かRubyみたいだぁ……

String.prototype.toUpperCase() = function() { return null }

"hoge".toUpperCase()
// => null