Taken from MDN:
nullas its prototype. By definition,
nullhas no prototype, and acts as the final link in this prototype chain.
Array you’ll see that the console prints out
Array.prototype . If you paste that into the console, you’ll see all the methods and properties that you have when creating a new array such as
push, filter, map .
Where this gets interesting is that we can then override these methods and all arrays that exist will now inherit the new overridden method! Let’s take a look at an example of this:
Let’s take a look at this snippet line by line.
- First we create an array called “items”
- We override the Array’s push method, this will override the push method for all arrays.
- We call the push method on the items array. This will then call the function that we defined which will call the console.log statement we defined.
If we now inspect the items array, we see that ‘grape’ was not added to the array. This functionality, in most cases is not desired. So let’s take a look as to how we can preserve the native functionality of the push method.
Let’s examine the changes that were made.
- On line 4 we store a reference to the native Array push method.
- On line 9 we use the stored reference to push the item into the array. (The reason this works is because on line 9 when we use
thisrefers to the items array.)
Now we have an example of preserving the native functionality, but we now have a log statement whenever an item is pushed into an array. This doesn’t have to be a log statement, we can also put in an if statement that checks if the item we’re trying to push is a string and if it isn’t we return early and don’t add it to the array.
The reason this is controversial is because it’s considered bad practice to override native prototypes. In my opinion, this is true only when you’re overriding the ENTIRE native object (e.g.
window.Object = 10 where subsequent calls to
Object will now return 10). This can cause a tremendous amount of bugs if you use other libraries that depend on the existence of the native Object. In the example I outlined above, however, we are overriding a method and additionally, we were careful to make sure that we actually restored native functionality to the methods so no harm is done.
That’s it for this part, in the next one we’ll dive deeper into native overrides and take a look at overriding some methods on the
Node prototype. We’re going to do some really cool things so be on the lookout.