Reputation: 791
Why in MDN functions polyfills use "if (!Array.prototype.filter)" ?
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
'use strict';
var t = Object(this);
var len = t.length >>> 0;
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
What do you need to use it?
Upvotes: 3
Views: 68
Reputation: 1074495
That's how they check to see if the thing they're polyfilling is already present.
To use that specific example: Array.prototype
refers to the object that is the prototype of all arrays. So Array.prototype.filter
is the property that arrays inherit that provides the filter
method. By doing if (!Array.prototype.filter)
, the code checks to see if that property already exists with a truthy value (a function reference is truthy) and doesn't try to add it if it's present. Reading the value of Array.prototype.filter
will yield undefined
(a falsy value) if filter
isn't present on Array.prototype
, which tells the code it needs to add the polyfill.
Upvotes: 2
Reputation: 171669
What do you need to use it?
if the native method does exist the polyfill doesn't overwrite it
Upvotes: 1