Polyfill Question [Solved]

I’ve written polyfills before, but not with an object. I’m simply trying to write a Object polyfill to test for isObject. The function looks like:

// isObject(obj): Test for object
// https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript#8511350
export function isObject(val) {
  if (val === null) { return false;}
  return ( (typeof val === 'function') || (typeof val === 'object') );
}

My polyfills however, look like this (in the MDN style, mostly cpy/pasted from SO).

if (!Array.prototype.merge) {
  // merge(array1, array2) + uniqueness
  // http://stackoverflow.com/a/28631880/5566775
  Array.prototype.merge = function(/* variable number of arrays */) {
    for(var i = 0; i < arguments.length; i++) {
      var array = arguments[i];
      for(var j = 0; j < array.length; j++){
        if(this.indexOf(array[j]) === -1) {
          this.push(array[j]);
        }
      }
    }
    return this;
  };
}

How do I make my Object polyfill like the Array polyfills? I understand this is trivial, but I want to understand how someone else would do it, so can use for my more complex use case.

Edit: the Array polyfill is in my custom polyfills.js file. I want to add a new custom polyfill so i can use the isObject globally.

I didn’t think there was an isObject method or proposal on JS to polyfill!

Generally I allow Meteor to perform any polyfilling required, either through babel transpilation, babel-runtime, or core-js
Outside of a Meteor environment I’d probably do something like the example for Array.prototype.merge

It is not a method or proposal - I’m trying to create it as a custom polyfill so i can use it all over the place. But I don’t know how to write polyfills unfortunatly.

A polyfill by definition fills in a missing implementation of the standard. So this would not be a polyfill

I’d caution you against extending native objects using the prototype, especially the Object.prototype which lives at the top of almost every inheritance chain.

Instead I would keep the first code block the same and import it where needed.

OR if you truly want to make it available without import, add it to the window as a global variable:

window.isObject = isObject;

Otherwise you could use an existing utility library like lodash or underscore that have functions like this already

Much appreciated. I think the smart way to do it is to use lodash or underscore, but just use the specific functions as per an es6 style import. Let me give that a go.

Had not considered the impact of extending native objects, currently do it in terms of stealing polyfills off MDN, so probably fine. Much appreciate super quick response.

1 Like