aboutsummaryrefslogtreecommitdiff
path: root/files/fa/web/javascript/reference/classes/index.html
blob: e031309f9fcef102116e354ae73be5093ede9ee5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
---
title: Classes
slug: Web/JavaScript/Reference/Classes
tags:
  - Classes
  - Constructors
  - ECMAScript 2015
  - Guide
  - Inheritance
  - Intermediate
  - JavaScript
  - NeedsTranslation
  - TopicStub
translation_of: Web/JavaScript/Reference/Classes
---
<div>{{JsSidebar("Classes")}}</div>

<p>Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 classalike semantics.</p>

<h2 id="Defining_classes">Defining classes</h2>

<p>Classes are in fact "special <a href="/en-US/docs/Web/JavaScript/Reference/Functions">functions</a>", and just as you can define <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expressions</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function declarations</a>, the class syntax has two components: <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">class expressions</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class declarations</a>.</p>

<h3 id="Class_declarations">Class declarations</h3>

<p>One way to define a class is using a <strong>class declaration</strong>. To declare a class, you use the <code>class</code> keyword with the name of the class ("Rectangle" here).</p>

<pre class="brush: js notranslate">class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}</pre>

<h4 id="Hoisting">Hoisting</h4>

<p>An important difference between <strong>function declarations</strong> and <strong>class declarations</strong> is that function declarations are <a href="/en-US/docs/Glossary/Hoisting">hoisted</a> and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a {{jsxref("ReferenceError")}}:</p>

<pre class="brush: js example-bad notranslate">const p = new Rectangle(); // ReferenceError

class Rectangle {}
</pre>

<h3 id="Class_expressions">Class expressions</h3>

<p>A <strong>class expression</strong> is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) {{jsxref("Function.name", "name")}} property, though).</p>

<pre class="brush: js notranslate">// unnamed
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// output: "Rectangle"

// named
let Rectangle = class Rectangle2 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// output: "Rectangle2"
</pre>

<div class="note">
<p><strong>Note:</strong> Class <strong>expressions</strong> are subject to the same hoisting restrictions as described in the <a href="#Class_declarations">Class declarations</a> section.</p>
</div>

<h2 id="Class_body_and_method_definitions">Class body and method definitions</h2>

<p>The body of a class is the part that is in curly brackets <code>{}</code>. This is where you define class members, such as methods or constructor.</p>

<h3 id="Strict_mode">Strict mode</h3>

<p>The body of a class is executed in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript.</p>

<h3 id="Constructor">Constructor</h3>

<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor</a></code> method is a special method for creating and initializing an object created with a <code>class</code>. There can only be one special method with the name "constructor" in a class. A {{jsxref("SyntaxError")}} will be thrown if the class contains more than one occurrence of a <code>constructor</code> method.</p>

<p>A constructor can use the <code>super</code> keyword to call the constructor of the super class.</p>

<h3 id="Prototype_methods">Prototype methods</h3>

<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>.</p>

<pre class="brush: js notranslate">class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100</pre>

<h3 id="Static_methods">Static methods</h3>

<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> keyword defines a static method for a class. Static methods are called without <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)" title='An example of class instance is "var john = new Person();"'>instantiating </a>their class and <strong>cannot </strong>be called through a class instance. Static methods are often used to create utility functions for an application.</p>

<pre class="brush: js notranslate">class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;

    return Math.hypot(dx, dy);
  }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
p1.distance; //undefined
p2.distance; //undefined

console.log(Point.distance(p1, p2)); // 7.0710678118654755
</pre>

<h3 id="Binding_this_with_prototype_and_static_methods">Binding <code>this</code> with prototype and static methods</h3>

<p>When a static or prototype method is called without a value for <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, such as by assigning a variable to the method and then calling it, the <code>this</code> value will be <code>undefined</code> inside the method. This behavior will be the same even if the <code><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">"use strict"</a></code> directive isn't present, because code within the <code>class</code> body's syntactic boundary is always executed in strict mode.</p>

<pre class="brush: js notranslate">class Animal {
  speak() {
    return this;
  }
  static eat() {
    return this;
  }
}

let obj = new Animal();
obj.speak(); // the Animal object
let speak = obj.speak;
speak(); // undefined

Animal.eat() // class Animal
let eat = Animal.eat;
eat(); // undefined</pre>

<p>If we rewrite the above using traditional function-based syntax in non–strict mode, then <code>this</code> method calls is automatically bound to the initial <code>this</code> value, which by default is the <a href="/en-US/docs/Glossary/Global_object">global object</a>. In strict mode, autobinding will not happen; the value of <code>this</code> remains as passed.</p>

<pre class="brush: js notranslate">function Animal() { }

Animal.prototype.speak = function() {
  return this;
}

Animal.eat = function() {
  return this;
}

let obj = new Animal();
let speak = obj.speak;
speak(); // global object (in non–strict mode)

let eat = Animal.eat;
eat(); // global object (in non-strict mode)
</pre>

<h3 id="Instance_properties">Instance properties</h3>

<p>Instance properties must be defined inside of class methods:</p>

<pre class="brush: js notranslate">class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}</pre>

<p>Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:</p>

<pre class="brush: js notranslate">Rectangle.staticWidth = 20;
Rectangle.prototype.prototypeWidth = 25;
</pre>

<h3 id="Field_declarations">Field declarations</h3>

<div class="warning">
<p>Public and private field declarations are an <a href="https://github.com/tc39/proposal-class-fields">experimental feature (stage 3)</a> proposed at <a href="https://tc39.es">TC39</a>, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like <a href="https://babeljs.io/">Babel</a>.</p>
</div>

<h4 id="Public_field_declarations">Public field declarations</h4>

<p>With the JavaScript field declaration syntax, the above example can be written as:</p>

<pre class="brush: js notranslate">class Rectangle {
  height = 0;
  width;
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
</pre>

<p>By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.</p>

<p>As seen above, the fields can be declared with or without a default value.</p>

<p>See <a href="/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields">public class fields</a> for more information.</p>

<h4 id="Private_field_declarations">Private field declarations</h4>

<p>Using private fields, the definition can be refined as below.</p>

<pre class="brush: js notranslate">class Rectangle {
  #height = 0;
  #width;
  constructor(height, width) {
    this.#height = height;
    this.#width = width;
  }
}
</pre>

<p>It's an error to reference private fields from outside of the class; they can only be read or written within the class body. By defining things which are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may change version to version.</p>

<div class="note">
<p>Private fields can only be declared up-front in a field declaration.</p>
</div>

<p>Private fields cannot be created later through assigning to them, the way that normal properties can.</p>

<p>For more information, see <a href="/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields">private class fields</a>.</p>

<h2 id="Sub_classing_with_extends">Sub classing with <code>extends</code></h2>

<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> keyword is used in <em>class declarations</em> or <em>class expressions</em> to create a class as a child of another class.</p>

<pre class="brush: js notranslate">class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name); // call the super class constructor and pass in the name parameter
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
</pre>

<p>If there is a constructor present in the subclass, it needs to first call super() before using "this".</p>

<p>One may also extend traditional function-based "classes":</p>

<pre class="brush: js notranslate">function Animal (name) {
  this.name = name;
}

Animal.prototype.speak = function () {
  console.log(`${this.name} makes a noise.`);
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.

// For similar methods, the child's method takes precedence over parent's method</pre>

<p>Note that classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object, you can instead use {{jsxref("Object.setPrototypeOf()")}}:</p>

<pre class="brush: js notranslate">const Animal = {
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
};

class Dog {
  constructor(name) {
    this.name = name;
  }
}

// If you do not do this you will get a TypeError when you invoke speak
Object.setPrototypeOf(Dog.prototype, Animal);

let d = new Dog('Mitzie');
d.speak(); // Mitzie makes a noise.
</pre>

<h2 id="Species">Species</h2>

<p>You might want to return {{jsxref("Array")}} objects in your derived array class <code>MyArray</code>. The species pattern lets you override default constructors.</p>

<p>For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent <code>Array</code> object, instead of the <code>MyArray</code> object. The {{jsxref("Symbol.species")}} symbol lets you do this:</p>

<pre class="brush: js notranslate">class MyArray extends Array {
  // Overwrite species to the parent Array constructor
  static get [Symbol.species]() { return Array; }
}

let a = new MyArray(1,2,3);
let mapped = a.map(x =&gt; x * x);

console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array);   // true
</pre>

<h2 id="Super_class_calls_with_super">Super class calls with <code>super</code></h2>

<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code> keyword is used to call corresponding methods of super class. This is one advantage over prototype-based inheritance.</p>

<pre class="brush: js notranslate">class Cat {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Lion extends Cat {
  speak() {
    super.speak();
    console.log(`${this.name} roars.`);
  }
}

let l = new Lion('Fuzzy');
l.speak();
// Fuzzy makes a noise.
// Fuzzy roars.
</pre>

<h2 id="Mix-ins">Mix-ins</h2>

<p>Abstract subclasses or <em>mix-ins</em> are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.</p>

<p>A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:</p>

<pre class="brush: js notranslate">let calculatorMixin = Base =&gt; class extends Base {
  calc() { }
};

let randomizerMixin = Base =&gt; class extends Base {
  randomize() { }
};
</pre>

<p>A class that uses these mix-ins can then be written like this:</p>

<pre class="brush: js notranslate">class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>



<p>{{Compat("javascript.classes")}}</p>

<h2 id="Re-running_a_class_definition">Re-running a class definition</h2>

<p>A class can't be redefined. Attempting to do so produces a <code>SyntaxError</code>.</p>

<p>If you're experimenting with code in a web browser, such as the Firefox Web Console (<strong>Tools </strong>&gt;<strong> Web Developer </strong>&gt;<strong> Web Console</strong>) and you 'Run' a definition of a class with the same name twice, you'll get a <code>SyntaxError: redeclaration of let <em>ClassName</em>;</code>. (See further discussion of this issue in <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1428672">bug 1428672</a>.) Doing something similar in Chrome Developer Tools gives you a message like <code>Uncaught SyntaxError: Identifier '<em>ClassName</em>' has already been declared at &lt;anonymous&gt;:1:1</code>.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields">Public class fields</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields">Private class fields</a></li>
 <li>{{jsxref("Operators/super", "super")}}</li>
 <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li>
 <li><a href="https://github.com/tc39/proposal-class-fields">Fields and public/private class properties proposal (stage 3)</a></li>
</ul>