Today I Learned - Rocky Kev

TIL Prototypical Inheritance vs return functions

POSTED ON:

TAGS:

I always wondered about Prototypical Inheritance and why choose one pattern over another.

Prototypical Inheritance

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

Via the MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

In other words -- everything in Javascript is built off of something else. Hidden in each element is a prototype. And it'll keep digging down the it doesn't, it'll come out to null.

This element in the DOM, inside Javascript, has a protype.

(Prototype is the object that is used to build __proto__ (dunderproto) when you create an object with new. ref )

Prototypical Inheritance Question

So the question I have is, why use prototypes?

function prototypeCalculator() {
this.value = 0
}

Calculator.prototype.add = function add(num1, num2) {
return num1 + num2
}

Calculator.prototype.subtract = function subtract(num1, num2) {
return num2 - num1
}

Versus this way?

function returnCalculator() {
let value = 0

return {
add(num1, num2) {
return num1 + num2
},
subtract(num1, num2) {
return num2 - num1
},
}
}

The answer is that prototypeCalculator() -- when you use it or extend it (like in OOP), it will always return back to the original add() and subtract() method.

The returnCalculator() -- when you use it or extend it, it will create new add() and subtract() functions and then get rid of them.

Honestly, for many use-cases, it's un-necessary to to consider the performance. Since we're talking about the difference between fractions of milliseconds.

IMO - the returnCalculator() is more human-readable, and contains the code into one spot. But the use-case of going with prototypeCalculator() would be in libraries, and to refactor the original function for performance.

REFERENCE:
https://jsmanifest.com/power-of-flyweight-design-pattern-in-javascript/


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.