0
0

More than 1 year has passed since last update.

javascriptのprototypeの超簡単まとめ

Last updated at Posted at 2022-09-06

javascriptのprototypeについて

prototypeは、javascriptの中でも理解しにくい概念でもあるが、実はjavasciptを理解するための重要な概念でもある。

prototypeを理解することで、javascriptの仕組みを理解することができる。

基本的なprototypeと__proto__

以下はjavascriptのprototypeの概念を図にしたものである。
開発者がPersonというクラスを定義すると、内部ではPersonPerson's prototypeobjが生成される。この二つのobjはお互いに関連することを示すためprototypeconstructorを持って相互参照する。

スクリーンショット 2022-09-06 17.16.22.png

constructorは、personが何によって作られたのかを示すもの。Person’ prototypePersonによって作られたことを示すため、constructorは内部的にPersonを参照する。

new キーワードをもってPersonを生成すると、person1の内部には__proto__が自動生成される。そして、__proto__person1の原型(Person)を示すprototypeを参照する。

つまり

簡単に説明はしたものの、これで理解できる人はあんまりないだろう。
結果的には何がどうなったのかを説明すると以下のことができるという意味である。

__proto__とclassのprototypeは以下の関係である。

javascript
person1.__proto__ === Person.prototype //true

表現を変えると以下のようにもできる

javascript
person1.__proto__.constructor === Person //true

__proto__のconstructorがPersonクラスそのものを指すので以下のこともできる。

javascript
const person2 = new person1.__proto__.constructor()
person2.__proto__ === Person.prototype //true

Classとprototypeでのconstructorの違い

Classでのconstructorは、インスタンスの生成時に初期化するためのもの。ここでのthisはnewでインスタンスを生成する際にClassを指し、constructorで記載した変数は、インスタンスを生成時にセットされ、変数に代入される。

ptorotypeでのconstructorは、prototypeの元となるClassを指す。

0
0
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
0
0