回答編集履歴

1

コンストラクタ、インスタンスの節を追記

2016/12/08 09:35

投稿

think49
think49

スコア18162

test CHANGED
@@ -5,6 +5,10 @@
5
5
  JavaScript における「オブジェクト」は「**Object 型**」に分類されるものを指します。
6
6
 
7
7
  「型」を識別するものとして「**typeof 演算子**」がありますが、JavaScript の typeof 演算子は特殊で分かりづらいので `Object()` を利用して判別する事をお勧めします。
8
+
9
+
10
+
11
+ - [12.5.5The typeof Operator - ECMAScript® 2016 Language Specification](http://www.ecma-international.org/ecma-262/7.0/#sec-typeof-operator)
8
12
 
9
13
 
10
14
 
@@ -20,7 +24,7 @@
20
24
 
21
25
 
22
26
 
23
- console.log(isObject(function () {})); // true
27
+ console.log(isObject(function () {})); // true (Object 型 -> 関数)
24
28
 
25
29
  console.log(isObject({}); // true
26
30
 
@@ -44,7 +48,109 @@
44
48
 
45
49
 
46
50
 
51
+ ### コンストラクタ
52
+
53
+
54
+
55
+ 「`new` 演算子で呼び出し可能な関数」を**コンストラクタ**と呼びます。
56
+
57
+ 関数は Object 型なので、必然的にコンストラクタも Object 型です。
58
+
59
+
60
+
61
+ ```JavaScript
62
+
63
+ function Person (n) { // Constructor
64
+
65
+ this.name = n;
66
+
67
+ return this; // opt.
68
+
69
+ }
70
+
71
+
72
+
73
+ console.log(Object(Person) === Person); // true (Object 型 -> 関数)
74
+
75
+ ```
76
+
77
+
78
+
79
+ ### インスタンス
80
+
81
+
82
+
83
+ コンストラクタを new 演算子で呼び出した返り値を**インスタンス**と呼びます。
84
+
85
+ インスタンスは必ず、Object 型です。
86
+
87
+
88
+
89
+ ```JavaScript
90
+
91
+ function Person (n) { // Constructor
92
+
93
+ this.name = n;
94
+
95
+ return this; // opt.
96
+
97
+ }
98
+
99
+
100
+
101
+ var p1 = new Person('Hanako');
102
+
103
+ console.log(Object(p1) === p1); // true (Object 型)
104
+
105
+ ```
106
+
107
+
108
+
109
+ > オブジェクトを使用するためにオブジェクトを複製したコピーをインスタンスと呼び、new演算子によりインスタンスを作ることができる。
110
+
111
+
112
+
113
+ インスタンスとはコンストラクタのコピーではありません。
114
+
115
+ オブジェクトのプロパティ参照時には**プロトタイプチェーン**によってプロトタイプ上のプロパティが参照されます(プロパティをコピーしているわけではありません)。
116
+
47
- - [12.5.5The typeof Operator - ECMAScript® 2016 Language Specification](http://www.ecma-international.org/ecma-262/7.0/#sec-typeof-operator)
117
+ https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain
118
+
119
+
120
+
121
+ ```JavaScript
122
+
123
+ function Person (n) { // Constructor
124
+
125
+ this.name = n;
126
+
127
+ return this; // opt.
128
+
129
+ }
130
+
131
+
132
+
133
+ Person.prototype = {
134
+
135
+ honorific: 'さん',
136
+
137
+ getName: function getName () {
138
+
139
+ return this.name + this.honorific;
140
+
141
+ }
142
+
143
+ };
144
+
145
+
146
+
147
+ var p1 = new Person('Hanako');
148
+
149
+ console.log(p1.getName
150
+
151
+ === Person,prototype.getName); // true
152
+
153
+ ```
48
154
 
49
155
 
50
156