OOP - GradedJestRisk/js-training GitHub Wiki
Object oriented is considered here to imply:
- objects
- message passing
Alan Kay, who coined the OOP, that object-oriented programming is more about messages than objects. The key is that programs are designed as a set of objects that communicate through messages. In many languages a message is referred to as a polymorphic method call. When:then
- a message is sent to an object;
- the object hasn't a method matching the message's signature;
- in a class-based language (eg. Smalltalk), check (recursively) if any of the object's base classes contains a method matching the method signature
- in prototype-based language (eg. JavaScript), a pattern known as delegation is used to transfer control to another object, known as a prototype.
2 ways:
JS does not require such an abstract thing as a class: everything is an object !
In JS, an object include:
- behaviour, in function;
- state, in primitive values.
- share behaviour (function)
- not to share state.
- this
- prevent object state corruption
However, if you want to store the behaviour (function) once, to save space in memory, you'll have to rely to language-dedicated feature:
- the
new
operator - constructor functions.
- specify behaviour
- describing state.
new
operator is used to create new instances based off a constructor function. Then, the constructor function that instantiated the object is called a prototype.
To implement prototype, see here
JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does NOT introduce a new object-oriented inheritance model to JavaScriptSource: MSDN