20
JavaScript Proto and Prototype ⚙️
Javascript can be described as a prototype-based language. This stems from an object's ability to have a prototype object, which allows them to inherit features from one another. You can read more about this in the MDN Web Docs.
But if you've ever looked at an arrary in your console, you may notice __proto__, what exactly is that?
If you don't already, open up your browser console. Now, create an empty array ([]). After you create the array, expand it using the > icon. Viola! You will see the **proto** attribute.
[]
length: 0
__proto__: Array(0) // <--- Here it is!
length: 0
constructor: ƒ Array()
concat: ƒ concat()
It does not matter how you create your array, you'll always find the proto attribute.
let example = [1,2,3,4,5]
example
(5) [1, 2, 3, 4, 5]
0: 1
1: 2
2: 3
3: 4
4: 5
length: 5
__proto__: Array(0) <-- woah! There it is again!
Every time we construct a new array, it uses the Array constrcutor, so proto looks for an array blueprint. It references all properties and methods from that blueprint. If you type Array.prototype, you'll see same method list as the one above.
Proto is Javascript's way to reference to the original prototype. And this applies to any react object!
Let's try out another example...
Object.prototype
{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
Boom! All the methods and properties.
Believe it or not, you can actually add your own methods to the Array blueprint.
Array.prototype.phrase = () => console.log("I like math")
Now any existing array will have this phrase method, including the example array we just created:
(5) [1, 2, 3, 4, 5]
0: 1
1: 2
2: 3
3: 4
4: 5
length: 5
__proto__: Array(0)
phrase: () => console.log("I like math") <--- Magic.
If you were to call the phrase method...
example.phrase() // "I love math"
- Everything in javascript references methods/properties from its blueprint.
- You can add and modify prototype features in the blueprint.
- Proto references the original blueprint's prototype features.
While there is more to dig into, this covers the basics of Javascript prototype and what it has to offer. Thanks for reading!
20