Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

JavaScript being (proto)typical JavaScript

7 min readAug 31, 2024

--

Press enter or click to view image in full size
The cat explaining the prototype chain

Once upon a time, while solving the leetcode exercises, I came across an interesting case upon which I had to research the rarely covered aspect of JavaScript — prototypal inheritance of the built-in types in JavaScript. Specifically, from this article you will see how to extend Map.prototype in the old-school way.

Prologue: While solving a leetcode exercise to refresh my JavaScript skills, I ran into a case where I needed to use a hashmap to track character occurrence count within a specific word. It’s more than possible to use a built-in Map type to achieve the behavior. However, I wanted the hash map to return a default value of 0 if the key does not exist, as I used to do so in Python with defaultdict(int). Luckily, JavaScript with its beauty offers a rich variety of options to implement this.

Let’s define the objectives of the default integer map:

  • The default integer map is required to return 0 on .get if the provided key does not exist.
  • The solution must be reusable.
  • The default map must be open for extension.

The easiest way — using ES6 classes

Spoiler: The ES 6 classes solution covers all the objectives:

  • Map can be extended by DefaultIntMap class.
  • The solution is reusable since we can create instances of DefaultIntMap class.
  • DefaultIntMap can be extended by other classes.

Relatively, it was easier to understand for myself since I’ve used a lot of programming languages offering “common modern” OOP syntax, such as Java, C#, Dart and etc. Moreover, the ES6 classes enhance the encapsulation of an object, you will see it later when we will come to the implementation of the function prototype.

class DefaultIntMap extends Map {
constructor() {
super();
}
get(key){
return super.get(key) ?? 0
}
}
const defaultIntMap = new DefaultIntMap()
console.log(defaultIntMap.get('a')) // prints 0

The code is readable for OOP people and works as expected.

Let’s explore the other ways.

Modifying the internal structure of an object

Let’s create an object of Map first:

const charCounterMap = new Map()

When we create the object using new Map(), the new object is allocated whose prototype equals Map.prototype under the hood.

// prints true
console.log(Object.getPrototypeOf(charCounterMap) === Map.prototype)

What is the advantage of having a prototype? When you call a method upon an object, JS engine first looks up the property among its immediate (internal, direct) listed properties. If it does not find the property, the engine looks it up among the properties of an object’s prototype.

// charCounterMap does not have its immediate .get method listed
console.log(Object.entries(charCounterMap))

// However, its prototype (Map.prototype) has .get so JS engines uses it.
// Hence, prototypes can extend behavior of an object
console.log(charCounterMap.get === Map.prototype.get)
console.log(charCounterMap.get('a'))

But can we override the .get ? Yes, we can. By defining the object’s own .get method property will make the engine use it over the prototype’s .get method property whereas the prototype’s property remains unaffected.

// Let's define charCounterMap's own .get property
charCounterMap.get = function (key){
// We want still to use the prototype's .get method but with a slight difference
// So we access the property of the prototype likes this
// Object.getPrototypeOf(this) will give Map.prototype
const prototypeGetMethod = Object.getPrototypeOf(this).get

// The method uses a referenece to "this" under the hood
//
// However, upon being extracted from prototype,
// Object.getPrototypeOf(this).get is not bound to any object
//
// So we need to bind it to "this" (hence, charCounterMap)
prototypeGetMethod = prototypeGetMethod.bind(this)

return prototypeGetMethod(key) ?? 0
}

// Now it gives false since the engine uses the immediate property
console.log(charCounterMap.get === Map.prototype.get)
// Now the .get method is listed among the immediate properties
console.log(Object.entries(charCounterMap))
console.log(charCounterMap.get('a')) // returns 0

Remember, I said how the ES6 classes enhance the encapsulation of an object?

Above you can see that I needed to bind the reference of charCounterMap by calling prototypeGetMethod.bind(this) so I can call the prototype method upon the charCounterMap object.

On the other hand, the ES6 classes have access to inherited prototype properties just by calling super with the binding managed automatically.

Now we have the default map object charCounterMap which behaves as expected. Cool! However, I want it to be reusable. The most straightforward approach is to return the object from a factory, as:

const defaultMapFactory = () => {
const instance = new Map()

instance.get = function (key){
return Object.getPrototypeOf(this).get.bind(this)(key) ?? 0
}

return instance
}

const map1 = defaultMapFactory()
const map2 = defaultMapFactory()

// Different instances
console.log(map1 !== map2)

// prints 0
console.log(map1.get('a'))

I would call it a day but let’s see which of the 3 objectives were covered by the updated solution:

  • The default int map performs as expected, returning 0 as the default value for unregistered keys.
  • The solution is reusable since we can create instances of the map using the defaultMapFactory .

However, it becomes complicated to extract the new behavior for extension since it is burned in the instances. JS allows objects to be prototypes of other objects:

const defaultMapFactory = () => {
const innerMap = new Map()

innerMap.get = function (key){
return Map.prototype.get.bind(innerMap)(key) ?? 0
}

return innerMap
}

const map1 = defaultMapFactory()
const extended = {
__proto__: map1
}

console.log(extended.get('a'))

Let’s see what changed in the implementation:

  • We have to access Map.prototype.get explicitly since the reference to thiswill imply to extended instance. The prototype of extended is not Map.prototype anymore, it’s an object prototype of map1 . So if we keep Object.getPrototypeOf(this).get.bind(this) , it will cause the stack overflow error.
  • We need to bind the reference to innerMap object within Map.prototype.get.bind(innerMap) instead of binding this since this now points to extended and it’s not encapsulated as Map but innerMap is.

“JavaScript is not Rocket Science,” they said ahh. Is there a more established and systematic way to make prototypes extendable?

Get Kerim Amansaryyev’s stories in your inbox

Join Medium for free to get updates from this writer.

Yes!

Encapsulating the object using the function prototype

First, let’s define the constructor function:

function DefaultIntMap(){}

The function’s return type is void , however, if called with new — a new object will be created.

const defaultIntMap = new DefaultIntMap()

The prototype of the object is automatically set to DefaultIntMap.prototype :

// prints true
console.log(Object.getPrototypeOf(defaultIntMap) === DefaultIntMap.prototype)
// prints true
console.log(defaultIntMap instanceof DefaultIntMap)

If we look at the structure of the prototype, we will see it’s empty, hence, it doesn’t yet have any properties:

// prints {}
console.log(DefaultIntMap.prototype)

So let’s add the expected behavior:

function DefaultIntMap(){}

DefaultIntMap.prototype.get = function (key){
return Map.prototype.get.bind(this)(key) ?? 0
}

const defaultIntMap = new DefaultIntMap()

// Gives an error
console.log(defaultIntMap.get('a'))

Everything looks great, however, the method throws an error:

 Method Map.prototype.get called on incompatible receiver #<DefaultIntMap>

And it makes sense since we call Map.prototype.bind(this) whereas this (an instance of DefaultIntMap ) is not encapsulated as Map . It can be fixed by calling the parent prototype’s constructor function within DefaultIntMap constructor function.

function DefaultIntMap(){
// Gives an error
// Error: Constructor Map requires 'new'
Map.call(this)
}

With any other typical constructor functions it would work but not with Map . Let’s apply the straightforward solution by inserting new and returning the resultant map object:

function DefaultIntMap(){
return new Map()
}

DefaultIntMap.prototype.get = function (key){
return Map.prototype.get.bind(this)(key) ?? 0
}

const defaultIntMap = new DefaultIntMap()

// Now it does not give the error since defaultIntMap is encapsulated as Map
// But returns underfined
console.log(defaultIntMap.get('a'))

Here the new problem appears. If we do not return anything from constructor function, the prototype of allocated instance will automatically be assigned to the prototype object of calling function. However, if you return value from the constructor function, the prototype of the returned object will be preserved. Hence, DefaultIntMap.prototype.get will not be called from defaultIntMap since its prototype is Map.prototype .

// prints false
console.log(Object.getPrototypeOf(defaultIntMap) === DefaultIntMap.prototype)
// prints false
console.log(defaultIntMap instanceof DefaultIntMap)

So how to encapsulate the object, returned from the constructor function, as Map, and how to add the behavior of DefaultIntMap at the same time?

It’s the tricky part, I had to do a research to realize it:

function DefaultIntMap() {
// the object's internal structure was assembled by Map constructor
const originalMap = new Map()
// Then we change its prototype so it gets extended
// by behavior set by DefaultIntMap.prototype
Object.setPrototypeOf(originalMap, DefaultIntMap.prototype)
return originalMap
}

DefaultIntMap.prototype.get = function (key) {
return Map.prototype.get.bind(this)(key) ?? 0
}

const defaultIntMap = new DefaultIntMap()

console.log(defaultIntMap.get('a'))


// prints true
console.log(Object.getPrototypeOf(defaultIntMap) === DefaultIntMap.prototype)
// prints true
console.log(defaultIntMap instanceof DefaultIntMap)

// Here is the new error
// DefaultIntMap does not have this property
console.log(defaultIntMap.set('a', 5))

From here we sway to another problem. Even though we managed to encapsulate the instance as Map , its prototype does not inherit from Map.prototype , hence, it does not have properties of Map.prototype , such as set , put, etc. How to solve this?

And here we come to — Prototypal inheritance! We just need to set the prototype of DefaultIntMap.prototype (yes, a prototype of a prototype) to be Map.prototype , and then we can “override” the behavior we need.

Object.setPrototypeOf(DefaultIntMap.prototype, Map.prototype)
DefaultIntMap.prototype.get = function (key) {
return Map.prototype.get.bind(this)(key) ?? 0
}

Here is the final code:

function DefaultIntMap() {
const originalMap = new Map()
Object.setPrototypeOf(originalMap, DefaultIntMap.prototype)
return originalMap
}

Object.setPrototypeOf(DefaultIntMap.prototype, Map.prototype)

DefaultIntMap.prototype.get = function (key) {
return Map.prototype.get.bind(this)(key) ?? 0
}

const defaultIntMap = new DefaultIntMap()

console.log(defaultIntMap.get('a'))


// prints true
console.log(Object.getPrototypeOf(defaultIntMap) === DefaultIntMap.prototype)
// prints true
console.log(defaultIntMap instanceof DefaultIntMap)
// prints true since defaultIntMap has Map.prototype in the prototype chain
console.log(defaultIntMap instanceof Map)

Now we can extend other prototypes by DefaultIntMap.prototype. The last objective has been covered!

I believe this is the way the ES6 classes work under the hood.

As a bonus, let’s see the resultant prototype chain:

defaultIntMap {
// DefaultIntMap.prototype
__proto__: {
// Map prototype
__proto: {...},
get(key){...}
}
}

If you have read the article till this row, you are a legend!

You can launch me over the moons (of Jupiter) by supporting me on Buy me a Coffee.

Thank you, stay tuned!

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--