回答編集履歴
3
プロトタイプチェーン
test
CHANGED
@@ -92,6 +92,68 @@
|
|
92
92
|
|
93
93
|
- [プロトタイプ(prototype)によるJavaScriptのオブジェクト指向:CodeZine(コードジン)](http://codezine.jp/article/detail/222)
|
94
94
|
|
95
|
+
|
96
|
+
|
97
|
+
### プロトタイプチェーン
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
JavaScriptではプロパティ参照の際には**必ず**、プロトタイプチェーンを辿る事でプロパティを検索します。
|
102
|
+
|
103
|
+
(`new` 演算子とセットで説明されることが多いですが、これは `new` 演算子を使った場合限定の規則ではありません)
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
```JavaScript
|
108
|
+
|
109
|
+
'use strict';
|
110
|
+
|
111
|
+
function Person (name) {
|
112
|
+
|
113
|
+
this.name = arguments.length ? name : 'no name';
|
114
|
+
|
115
|
+
}
|
116
|
+
|
117
|
+
|
118
|
+
|
119
|
+
Person.prototype.output = function output () {
|
120
|
+
|
121
|
+
console.log(this.name);
|
122
|
+
|
123
|
+
};
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
var taro = new Person('taro');
|
128
|
+
|
129
|
+
|
130
|
+
|
131
|
+
taro.output(); // "taro" (new Person は Person.prototype に存在するプロパティを使用できる)
|
132
|
+
|
133
|
+
|
134
|
+
|
135
|
+
console.log(taro.output === Person.prototype.output); // true (taroのプロパティを参照する時、暗黙の内に Person.prototype に存在するプロパティを検索する)
|
136
|
+
|
137
|
+
console.log(Object.getPrototypeOf(taro) === Person.prototype); // true (new Person の [[Prototype]] は Person.prototype である)
|
138
|
+
|
139
|
+
console.log(taro.__proto__ === Person.prototype); // true (同上)
|
140
|
+
|
141
|
+
```
|
142
|
+
|
143
|
+
|
144
|
+
|
145
|
+
注目してほしいのは、`taro.output === Person.prototype.output` が `true` となる部分です。
|
146
|
+
|
147
|
+
`taro.output` が参照された場合、`taro` は直属のプロパティとして `output` を持っていない為、prototypeである `Person.prototype` から `output` プロパティを探し、見つかった為、それを参照しているわけです。
|
148
|
+
|
149
|
+
|
150
|
+
|
151
|
+
ここでもし、`Person.prototype.output` が存在しなかったのなら、更に上の prototype を探し、prototype が存在しなくなるまでこの過程を繰り返します。
|
152
|
+
|
153
|
+
この仕組みを**プロトタイプチェーン**といいます。
|
154
|
+
|
155
|
+
|
156
|
+
|
95
157
|
- [継承とプロトタイプチェーン - JavaScript | MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain)
|
96
158
|
|
97
159
|
|
2
Person -> Person\.prototype
test
CHANGED
@@ -84,7 +84,7 @@
|
|
84
84
|
|
85
85
|
JavaScriptは**プロトタイプベース**の言語です。
|
86
86
|
|
87
|
-
`Person` はオブジェクトの雛形(プロトタイプ)であり、`new Person` という命令によって、**Person を雛形(プロトタイプ)とするオブジェクトを生成**します。
|
87
|
+
`Person.prototype` はオブジェクトの雛形(プロトタイプ)であり、`new Person` という命令によって、**Person.prototype を雛形(プロトタイプ)とするオブジェクトを生成**します。
|
88
88
|
|
89
89
|
そうすることによって、`Person` の性質を持つオブジェクトを複数生成できます。
|
90
90
|
|
1
インスタンス生成元 ≠ \[\[Prototype\]\]
test
CHANGED
@@ -36,7 +36,9 @@
|
|
36
36
|
|
37
37
|
|``[[Call]]``を持っているか|持っている(関数である)|持っていない(関数ではない)|
|
38
38
|
|
39
|
+
|インスタンス生成元|`Function`|`Person`|
|
40
|
+
|
39
|
-
|
|
41
|
+
|[[Prototype]] (`__proto__`)|`Function.prototype`|`Person.prototype`|
|
40
42
|
|
41
43
|
|
42
44
|
|