prototype?
・継承を実現できる
・すべてのオブジェクト(複数の値をひとまとめにした値)がプロトタイプをベースに作られている。
・メモリの無駄消費を防げる
使用方法
宣言とオブジェクト構造
const Dog = function(name){
this.name = name;
}
const poti = new Dog('ポチ');
console.log(poti);
結果
Dog {name: "ポチ"}
メソッド定義
prototype使用
const Dog = function(name){
this.name = name;
}
Dog.prototype.getName = function(){
return this.name;
}
prototype未使用
const Dog = function(name){
this.name = name;
this.getName = function(){
return this.name;
}
}
prototypeを使用した場合と使用しない場合では、new されて違うインスタンスを生成した場合、使用した場合はプロトタイプを使って宣言したメソッドを参照するが、使わない場合だとgetNameがインスタンスの数分コピーされるので、無駄にメモリを消費する。
ただ、上記のプロトタイプを使った書き方をすると、ほかのプロトタイプなども作りたい場合まとまりがなくなっていってしまう。そこで違う書き方ができる。
const Dog = function(name){
this.name = name;
}
Dog.prototype = {
getName : function(){
return this.name;
}
};
こうすることで、対象のオブジェクトごとにまとめることができる。(プロトタイプを使用しながら)
参考にさせていただいたサイト