JS Prototype

JS Prototype

Prototype is an object that exists on constructor functions. It's used to define properties and methods that will be inherited by instances created from that constructor.

Let's break down how the string primitive 'Bruno' inherits and accesses the String prototype functions.

When you create a string primitive like this:

Article content

JavaScript does some behind-the-scenes magic to allow this primitive value to access String prototype methods. Here's how it works:

  1. Primitive Wrapper Objects: When you try to access a property or method on a primitive string, JavaScript temporarily converts the primitive to a String object. This process is called "boxing" or "wrapping".
  2. Prototype Chain: The temporary String object created has its __proto__ property set to String.prototype. This means it has access to all the methods defined on String.prototype.
  3. Method Invocation: When you call a method on the string, JavaScript looks up the prototype chain to find the method in String.prototype.
  4. Auto-boxing: After the method execution, the temporary object is discarded, and you're left with the primitive value again. This process is so seamless that you don't notice it happening.

Here's an example to illustrate:

Article content

You can see this inheritance in action:

Article content

All the methods available on String.prototype are accessible to name. You can see the full list of inherited methods like this:

Article content

This will output an object of all the method names available on String.prototype, which name can use.

It's worth noting that while name can use these methods, it doesn't actually have them as its own properties:

Article content

The toUpperCase method (and others) are found via the prototype chain, not as direct properties of nome.

This mechanism allows JavaScript to provide rich functionality to primitive values while keeping them lightweight and performant. It's a key part of JavaScript's prototype-based inheritance system.

Conclusion

In essence, the prototype system is a powerful and flexible feature of JavaScript that enables object-oriented programming paradigms, efficient code reuse, and dynamic behavior modification. Mastering prototypes is key to becoming proficient in JavaScript and unlocking its full potential as a language.

Bruno, thanks for sharing!

Like
Reply

Nice good tips! Thanks for sharing!

Useful tips, thanks for sharing

Fascinating explanation of JavaScript's prototype-based inheritance system, Bruno Anjos. Your analogy of 'boxing' and 'wrapping' primitive values to access String prototype methods is particularly helpful.

To view or add a comment, sign in

More articles by Bruno Anjos

Others also viewed

Explore content categories