- classes are just "special functions" (syntactical sugar)
- class declaration:
- "class" keyword : class NameOfClass {...
- "constructor" function: constructor (para1, para2) { this.property1 = para1...
- class declaration is not hoisted (unlike function), must define first, refer next
- class expression:
- var NameOfClass = class { constructor(para1, para2) {.....
- var NameOfClass = class NameOfClass { constructor(para1, para2) {.....
- body
- body in strict mode
- [experimental] public / private field declarations
- constructor
- can call "super(...);" to call parent
- instance property defined here: this.instanceProperty = 'a value'
- getter
- method
- someMethod(...) {...
- the methods are attached to the class object (function)'s prototype, so this equals
- TheClass.prototype.someMethod = function (...) {...
- static method - call without instantiating, cannot be called through class instance
- [outside body] TheClass.StaticProperty = 'must be defined outside'
- sub class
- class Dog extends Animal {
- constructor, if there's one in sub class, needs to first call super() before using "this"
- can extend traditional function based classes (no difference between class and function)
Is just a function.
Class has a property named 'prototype', note that the 'prototype' property of the class is NOT the class's prototype.
C.prototype // is C {}, a prototype where the methods are attached
Object.getPrototypeOf(C) // is [Function], since class is function
Methods are just functions attached to the class's 'prototype' property (not class's prototype)
ci.speaks === C.prototype.speaks // true: ci is an instance of C, speaks is a method
Class instance's prototype is the 'prototype' property of the class (function)
Object.getPrototypeOf(ci) === C.prototype // true
Instantiating an instance involves using the 'new' keyword. In fact it just (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new):
- creates a blank plain JS object
- links "constructor" to the function (i.e. the class)
- pass the newly created blank object as 'this' to the function
- returns 'this' (if constructor does not return its own)
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance