MV Don't add new methods to standard prototypes

So I basically did what the title suggests not to do and I had to learn my lesson due to an incompatibility with someone else's plugin.
Now I'd like to share my newly discovered expirience with you. This can be seen as advice or even as a discussion topic.
I guess pro javascript developers on this forum were already well aware of this and wouldn't have done it anyway, but maybe there are other noobs like me who think it might be convenient and actually didn't know you shouldn't extend standard types like Array.prototype as doing so might result in really strange problems and compatibility issues.
Now that I know that, I've found that even the Javascript documentation advises against it and multiple discussion on stackoverflow marking this as a bad practise.

To give an example what I mean, let's use Array.prototype, the type that I tried to extend:
JavaScript:
var x = [2,3,5];

for( let q in x )
{
    console.log(x[q]);
}

for( let q of x )
{
    console.log(q);
}

x.forEach(q => console.log(q));
If you save this as a plugin in your plugin folder and activate it, you'll get the following console output:
Spoiler: Result
1654877694206.png

So each of the three loops logs the same.

Now let's add a method to Array.prototype with the usual syntax:
JavaScript:
var x = [2,3,5];

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

for( let q in x )
{
    console.log(x[q]);
}

for( let q of x )
{
    console.log(q);
}

x.forEach(q => console.log(q));
Spoiler: Result
Array.prototype.test is a new function and surprise, surprise it is enumerable and therefore iterated over in the for..in loop, which is basically what I didn't know and also unknowlingly avoided by not using for..in loops over arrays. So general advice: Please don't use for..in loop for arrays either, it is meant for associative containers, but not for indexed arrays.
1654878105041.png

Use for..of loop or forEach function!

And to show you, what the problems was I had to deal with. The other plugin creator tried to iterate over an array of JSON-Formatted strings and parse them:
1654878276135.png

and my array extensions where causing the same parse error right at the start of the game, making it unable to start.

On stackoverflow some people suggest however you could basically extend standard types like this, at least without running into the for..in loop problem:
JavaScript:
Object.defineProperty(Array.prototype, "test", {
    value: function() {
        console.log("test");
    },
    configurable: false, // This is the default so not actually required
    enumerable: false // This is the default
});
Which results in the original console output.

But there are also people claiming even this as bad practise causing compatibility issues with others peoples code.
The general answer for not doing this either seems to be naming conflicts and unexpected behaviour if someone overrides your property, even though this can be avoided by leaving configurable = false.
Well actually not. If someone will not use properties, but overwrite Array.prototype.test with something else, like a function again, this will work, even tough configurable = false.
I think this might be an interesting discussion topic with pro javascript users. Would you also generally discourage people like me from adding stuff they think might be convenient to standard types in their publicly released plugins via properties?
seems to be naming conflicts and unexpected behaviour if someone overrides your property
that is not exactly unique to javascript, it is a problems with a lot of programming languages and options like aliasing.
but the solution is rather simple: personalize your function names.

no one can accidentally override your function if every programmer uses a different naming identifier.
For example in your case, do not name the method or function test but BuOtest (BuO short for BurningOrca).

That is where the practise of the function naming comes from, in VXAce every scripter had its own three-letter-code to apply to scriptnames and function names, like MOG from moghunter or YEA from yanfly (for Yanfly Engine Ace).
This is a teamworking/organisational principle.

The key point is that, in general, you cannot know how someone else will write their code. So, where possible, you should avoid adding things to any "public" area of the existing codebase. Examples include the global namespace as well as existing objects like Array or String.

For example, prefer this:

MyNamespace.firstArrayElement = function(arr) { return arr[0]; };
...over this:

Array.prototype.firstElement = function() { return this[0]; };

The core scripts define a few extensions of basic JavaScript objects, e.g. Array#contains, String#format, Number#padZero. That's OK because all plugins build on the core scripts: plugin authors can know those methods are defined.
I always work in a TLB namespace for this very reason.
that is not exactly unique to javascript, it is a problems with a lot of programming languages and options like aliasing.
but the solution is rather simple: personalize your function names.

no one can accidentally override your function if every programmer uses a different naming identifier.
For example in your case, do not name the method or function test but BuOtest (BuO short for BurningOrca).

That is where the practise of the function naming comes from, in VXAce every scripter had its own three-letter-code to apply to scriptnames and function names, like MOG from moghunter or YEA from yanfly (for Yanfly Engine Ace).
I already do that. I use BoMV and BoMZ for my new plugins as names (okay they have 4 letters instead of 3, but still). Only exception was trying to add something to Array.prototype.
This is a teamworking/organisational principle.

The key point is that, in general, you cannot know how someone else will write their code. So, where possible, you should avoid adding things to any "public" area of the existing codebase. Examples include the global namespace as well as existing objects like Array or String.

For example, prefer this:

MyNamespace.firstArrayElement = function(arr) { return arr[0]; };

...over this:

Array.prototype.firstElement = function() { return this[0]; };


The core scripts define a few extensions of basic JavaScript objects, e.g. Array#contains, String#format, Number#padZero. That's OK because all plugins build on the core scripts: plugin authors can know those methods are defined.
Interesting, I had a look into that part of the core scripts just now and they do it with the Object.defineProperties Syntax at least for the array. So I guess as long as I might use property names unique to me it isn't that much of a problem, but I'll try to avoid it. I've already changed the questionable plugin to use MyNamespace.function instead.

And this is totally true and would also apply if I would do
BoMZ.drawText = Window_Base.prototype.drawText; Window_Base.prototype.drawText = function(text, x, y, width, align) { BoMZ.drawText.call(this, text, x, y, width, align); console.log(42); } and someone else would just overwrite that function without aliasing. I can never be sure about my functions working the same ways for someone as they do for me. Only thing is they shouldn't cause crashes.[/icode]

Edit:
I'm still not really a fan of wrapping the entire plugin into a IIFE, so I'm still not really avoiding the global namespace where possible, but I'll take the advise to avoid it as much as possible.
I'm still not really a fan of wrapping the entire plugin into a IIFE, so I'm still not really avoiding the global namespace where possible, but I'll take the advise to avoid it as much as possible.
To be clear, I would generally recommend defining your code on a global namespace, e.g. BoMV. Doing so allows other plugins, by you and by other people, to interface with your code. You can still use an IIFE or whatever to keep some stuff private if you want. 👋

Might be worth mentioning Symbols here, too:
Symbol() generates a runtime-unique identifier, so you can use that to add guaranteed non-conflicting properties or methods to existing objects, e.g.
JavaScript:
// define symbol
const SYM = Symbol();
// define method using that symbol as an identifier
Array.prototype[SYM] = function() { console.log('first value is ' + this[0]); };
// call method on array [1,2,3]
[1,2,3][SYM]();
Note that by default JSON.stringify will skip Symbols, and they'll be skipped in other situations like for...in, Object.keys, etc. 😮‍💨
when it comes to IIFEs I'd actually recommend using them a lot. However, this is not necessarily for the scope limitation but more so because it allows you to use "strict mode" (and strict mode makes JavaScript significantly less awkward). What I usually do is to declare a shared namespace object outside the IIFE and then put everything else into the IIFE so that strict mode applies to it.

If you define stuff like "Game_Actor.prototype.someFunction" it will be applied to the Scope of Game_Actor anyways and as such remains visible. And if something needs to be visible, you can simply drop it into the namespace and everything is cool.

Oh, and if you define a "class"/constructor inside the enclosure and want it to be global, simply do this:

class SomeClass [extends SomeOtherClass] {
//blablabla
//more blablabla
}
window.SomeClass = SomeClass;

But ultimately, I'd say using or not using enclosures and/or namespaces comes down to personal preference. The important part is, that one should triy to minimize the risk of compatibility issues with other plugins

By the way, I really recommend dropping function aliases into that namespace as well because it REALLY helps with making plugins compatible with one another.

Original thread: https://forums.rpgmakerweb.com/threads/dont-add-new-methods-to-standard-prototypes.148402/