DEV Community

Bradley Black
Bradley Black

Posted on • Updated on

Javascript Prototypes DIY

What Are Prototypes?

Javascript prototypes scale up to the global level, and down to individual objects and elements coded into an environment. Global prototypes that come native to JS simply append to this object-oriented structure. Of course, coders can build upon this existing structure with their own prototypes.

So what are prototypes, and why use them?

Prototype methods are functionally the same as non-prototype methods, but, in most cases, prototype methods are the more efficient option. This is because non-prototype methods are copied within every instance of that datatype. The result is higher memory usage.

On the other hand, prototypes are stored as a single instance, thus taking up less memory.

The question of whether or not to use prototypes hinges on how frequently they’ll be accessed. If your method will only be used sporadically, then a prototype is probably the best bet. The native methods of JS also adhere to this approach.

These are (some of) the non-prototype methods for arrays:

Alt Text

And here are (some of) the prototypes:

Alt Text

Thinking Globally

In every JS environment, the global Object reigns, and all other complex data types inherit its prototypes. These complex data types themselves are objects, and they have access to their own set of methods and prototypes.

To see this in action, enter Object.prototype in the Dev Tools console.

Alt Text

For the global Window object, or any new objects that are created, these prototypes are available.

Now check the global Array prototypes by entering Array.prototypes. You’ll see a set of functions stored under the “proto” label.

Alt Text

Look familiar? You can see how the Array object has inherited all of the global Object’s prototypes. Notice these prototype methods are actually all functions. Also, notice how the functions have access to their own folder of global function prototypes.

Prototype DIY

Understanding this, you can see the functional symmetry between global objects and objects you code into a JS environment. Array methods and prototype methods are simply key/value pairs assigned to the global Array object, and, since they’re stored globally, any arrays you create will be able to access them.

Now we can, say, create a printMoney method that translates any array into dollar signs, and make it globally available for all arrays:

Alt Text

Top comments (0)