IE兼容之 remove()、assign()方法

324 阅读1分钟

场景

做IE兼容时候有很多方法和属性是缺失,整理一些修复的bug,之后会持续更新~

功能

兼容IE

代码

一般可以写在项目的起始文件中

  • assign
if (typeof Object.assign != 'function') {
  // Attention 1
  Object.defineProperty(Object, "assign", {
    value: function (target) {
      'use strict';
      if (target == null) { // Attention 2
        throw new TypeError('Cannot convert undefined or null to object');
      }

      // Attention 3
      var to = Object(target);
        
      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) {  // Attention 2
          // Attention 4
          for (var nextKey in nextSource) {
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
  console.log('添加了assign方法')
}
  • remove

在antv当中遇到的bug于是重写了remove方法

if (window.Element) {
  // remove
  if (Object.getOwnPropertyNames(Element.prototype).indexOf('remove') === -1) {
    if (!('remove' in Element.prototype)) {
      Element.prototype.remove = function () {
        if (this.parentNode) {
          this.parentNode.removeChild(this);
        }
      };
    }
  }
};