2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptのprototype宣言・使用

Last updated at Posted at 2019-12-15

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;
    }
};

こうすることで、対象のオブジェクトごとにまとめることができる。(プロトタイプを使用しながら)

参考にさせていただいたサイト

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?