|
1 | 1 | # About |
2 | 2 |
|
3 | | -... |
| 3 | +JavaScript includes the capabilities for object-oriented programming ([OOP][wiki-oop]). Usually languages realize those features by providing classes and objects as instances of those classes. |
| 4 | + |
| 5 | +JavaScript on the other hand did not have classes at all before they were added to the language specification in 2015. And even though a `class` keyword is available nowadays, JavaScript is still a _prototype-based_ language. |
| 6 | + |
| 7 | +To understand what that means and how JavaScript actually works, we will go back to the time without classes. |
| 8 | + |
| 9 | +## Prototype Syntax |
| 10 | + |
| 11 | +In OOP, you want to create objects from "templates" so that they include certain data and functionality. The data (keys in the object) are called _properties_ in the OOP context, the functionality (functions included in the object) are called _methods_. |
| 12 | + |
| 13 | +### Constructor Function |
| 14 | + |
| 15 | +In JavaScript, the template is facilitated by a regular function. Used in this context, it is called a _constructor function_ and the function name should start with a capital letter. Instances (objects) are derived from the template using the `new` keyword when invoking the constructor function. |
| 16 | + |
| 17 | +```javascript |
| 18 | +function Car() { |
| 19 | + // ... |
| 20 | +} |
| 21 | + |
| 22 | +const myCar = new Car(); |
| 23 | +const yourCar = new Car(); |
| 24 | +``` |
| 25 | + |
| 26 | +### Instance Properties |
| 27 | + |
| 28 | +Often, you want all the derived objects to include some properties and pass some initial values when the object is constructed. This is facilitated via the `this` keyword. Inside the constructor function, `this` references the new object that will be created via `new` and it is automatically returned from the function. |
| 29 | + |
| 30 | +That means we can add properties to the new instance by adding them to `this` in the constructor function. |
| 31 | + |
| 32 | +```javascript |
| 33 | +function Car(color, weight) { |
| 34 | + this.color = color; |
| 35 | + this.weight = weight; |
| 36 | + this.canDrive = true; |
| 37 | + // implicit "return this" happens here |
| 38 | +} |
| 39 | + |
| 40 | +const myCar = new Car('red', '2mt'); |
| 41 | +myCar.color; |
| 42 | +// => 'red' |
| 43 | +myCar.canDrive; |
| 44 | +// => true |
| 45 | +``` |
| 46 | + |
| 47 | +### Instance Methods |
| 48 | + |
| 49 | +TODO continue here |
| 50 | + |
| 51 | +- can be added via this or via prototype |
| 52 | +- instance holds reference to prototype |
| 53 | +- prototype can change dynamically |
| 54 | + |
| 55 | +## Class Syntax |
| 56 | + |
| 57 | +- same as above in new syntax |
| 58 | +- public/private |
| 59 | + |
| 60 | +Other |
| 61 | + |
| 62 | +- class properties/methods |
| 63 | + |
| 64 | +[wiki-oop]: https://en.wikipedia.org/wiki/Object-oriented_programming |
0 commit comments