es6をもっとを体得する前に
まずes5のプロトタイプを書いて復習しよう思ったのでメモです。
基本を復習
↓すごくわかりやすい説明でした
JavaScriptの「プロトタイプ入門」
http://qiita.com/takeharu/items/809114f943208aaf55b3
sample
// Personクラス
var Person = function(aName){
this.name = aName;
this.hello = function(){
console.log('こんにちは、私は' + this.name + 'です');
}
};
var John = new Person('ジョン');
var Paul = new Person('ポール');
console.log(John === Paul); // false
console.log(John.hello === Paul.hello); // false
// プロトタイプで書いてみる
var Person = function(aName){
this.name = aName;
}
Person.prototype.hello = function(){
console.log('こんにちは、私の名前は' + this.name + 'です');
};
var John = new Person('ジョン');
var Paul = new Person('ポール');
console.log(John === Paul); // false
console.log(John.hello === Paul.hello); // true
console.log(John.hello === Paul.hello) がtrue になる!
hello()の挙動は一緒なので、個別で持つ必要なし。親にひとつあればよし。
メモリの節約。
継承してみる
sample
// プロトタイプ継承してみる
// アニマル ← 犬
// Animalクラス
var Animal = function(aName){
this.name = aName;
};
Animal.prototype = {
voice: 'ギャオー',
bark: function(){
console.log(this.voice + 'と鳴いた');
}
};
// Dogクラス
var Dog = function(aVoice){
this.voice = aVoice;
}
// Animalクラスを継承
Dog.prototype = new Animal();
var dog = new Dog('わんわん!');
dog.bark(); // わんわん!と鳴いた
オーバーライド
子クラス内で親クラスのメソッドを上書きする
(親クラスのメソッドは影響を受けない)
sample
// オーバーライドしてみる
var Human = function(aName){
this.name = aName;
};
Human.prototype.greeting = function(){
console.log('はじめまして、私は' + this.name + 'です');
};
var John = function(){
this.name = 'ジョン';
this.super = Human.prototype;
}
John.prototype = new Human();
// オーバーライド
John.prototype.greeting = function(){
console.log('今後ともよろしくおねがいします' + this.name + 'です');
// this.super.greeting.call(this); (子クラスから親クラスのgreetingメソッドを呼ぶ)
};
var jhon = new John();
jhon.greeting(); // 今後ともよろしくおねがいしますジョンです
// こっちは影響うけない
var paul = new Human('ポール');
paul.greeting(); // はじめまして、私はポールです。
完