Adding a function to Array.prototype in IE results in it being pushed in to every array as an element

前端 未结 1 1538
广开言路
广开言路 2021-01-12 05:58

I have added the following polyfill to Array in the beginning of my project:

if (!Array.prototype.find) {
  Array.prototype.find = function(pred         


        
相关标签:
1条回答
  • 2021-01-12 06:49

    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.

    0 讨论(0)
提交回复
热议问题