Skip to main content

Classes & Prototypes (OOP)

OOP ⇒ a paradigm for structuring complex code

Prototype chain ⇒ the feature behind the scenes that enables emulation of OOP

difference between proto and prototype

new and class keywords

object.prototype

what’s the new keyword doing under the hood?

Programming paradigms provide:

  1. Easy to reason about
  2. Easy to add new features
  3. Efficient and performant

Objects ⇒ store functions with their associated data (encapsulation)

functions in objects are called methods.

Object.create(null) ⇒ {}

factory function ⇒ create & generate objects from a function

Untitled

There are problems with the approach used in upper image.

  1. Each user we create, we have the increment function (same functionality) stored for each of these objects. We could have only 1 of this function.
  2. If in the future we want to add a functionality, we need to manually add it for all the objects.

Untitled

Untitled

Screenshot 2023-08-18 at 22.39.37.jpg

Untitled

Object.create(functionStore)

This object will have an unremovable link to the functionStore

Untitled

Object.create creates an empty object always.

A hidden propert in this object ( proto ), provides a proto link to the functionStore object. This link allows the object to look for properties not on object to be looked at proto object. Through its proto reference link. (prototype chain)

This way, this code is saved in memory only once, and we don’t need to waste memory for every object.

use of ‘this’ in functionStore ⇒ automatically you get an implicit parameter ‘this’ that is assigned to the object on left-hand side.

JS’s prototype feature: If you can’t find the function, look for linked ones

Object.prototype ⇒ is an object. All objects in JS has a proto property containing useful functions.

.hasOwnProperty() ⇒ one of those functions.

Object.create() lets us have control over the proto property.

Object.prototype’s proto is null.

Arrow functions & this ⇒ Arrow functions - this assignment are automatically lexically scoped. ‘this’ will be determined by where the function is saved.

(if it’s not an arrow function, this will assigned to global (bad language design?)

Untitled

If you’d use an arrow function for increment, ‘this’ would have referred to where the function is created. which is the global.! this is the important difference between where and when to use arrow functions.

This is what happens behind the scenes. But is not standard. The standard is

new

All this can be automated with ‘new’

class

It’s a syntactic sugar. ES6 ES2015

Untitled

We used to declare the function and the function object that are combined later separately.

To do these together, we can use class.

Screenshot 2023-08-19 at 02.16.41.jpg

Screenshot 2023-08-19 at 02.21.24.jpg