4

As the questions says, is it possible to replace such functions with an own implementation?

Like:

Array.prototype.forEach = function () {
    console.log("foo");             
};                         

That's - of course - a stupid replacement. But this is more about the possibility. I tried it, but then it seemed like at runtime it's not replaced.

My console logs the foo. But when I'm calling something like

[].forEach();

which also shout log foo, it does not work, until I replace the forEach function again in the console.

Johannes Klauß
  • 9,087
  • 13
  • 59
  • 110

2 Answers2

6

Your example works:

Array.prototype.forEach = function () {
    alert("foo");             
};    

[].forEach();

http://jsbin.com/xidew/1/

This is ultimately, undesirable though. You are altering the fundamental functions on which applications and libraries work. If you do alter these functions, you must be cautious to not break the way existing functions depend on them.

Looking at the way underscore.js edits forEach:

You can see that they avoided changing the way every array uses forEach by creating a separate _.forEach() function.

Then other libraries, like Backbone, take that forEach and only override their subclass of array. Like Backbone overrides the forEach method in the Backbone collection.

The moral of this story is:

Its an extremely rare case to modify the prototype of base object classes, String, Array, Object, because of the possibly cataclysmic implications. If you need to, you can create a subclass of those base classes and modify it there to suit your own purposes. This tactic of subclassing is evident in Backbone and other popular and widely used js libraries.

agconti
  • 15,820
  • 15
  • 69
  • 108
0

What you could do is add the code to an external file default.js and add an script tag to the layout html (the main page that all the rest of the pages use)

<head>
    <title>Title</title>
    <link href="Content/default.css" rel="stylesheet" />
    <script src="Scripts/default.js"></script>
</head>

It will always be picked up by other js code as it will be always loaded in the page.

ChemaMX
  • 126
  • 1
  • 4