I have added the following polyfill to Array
in the beginning of my project:
if (!Array.prototype.find) {
Array.prototype.find = function(pred
It's not being "pushed" into every array; you added a property to the prototype object, so it's visible and enumerable in every array instance. That's how prototype properties are supposed to work.
It works in Chrome and Firefox because .find()
on the prototype in those environments is defined in such a way as to be visible but not enumerable. You can do that in IE by using Object.defineProperty()
:
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, "find", {
value: function(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
}
});
}
In addition to property "value", which is clearly the value of the new property, the properties "enumerable" and "configurable" default to false
. That means that "find" won't show up in any situation that involves iterating through object properties.