# Object

更多关于polyfill的实现可参见github - ECMAScript Shims

# Object.assign

/**
 * Object.assign
 *
 * 拷贝源对象自身的并且可枚举的属性到目标对象身上,注意以下几点:
 *    - 该方法使用源对象的 [[ Get ]] 和目标对象的 [[ Set ]],所以它会调用相关 getter 和 setter。因此,它分配属性而不是复制或定义新的属性。如果合并源包含了 getter,那么该方法就不适合将新属性合并到原型里
 *    - 继承属性和不可枚举属性是不能拷贝的
 *    - 浅拷贝,非深度拷贝
 *    - 如果 source 是原始类型,会被包装成 object
 *
 * Reference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
 */
if (typeof Object.assign != 'function') {
  Object.assign = function(target) {
    'use strict';
    if (target == null) {
      throw new TypeError('Cannot convert undefined or null to object');
    }

    target = Object(target);
    for (var index = 1; index < arguments.length; index++) {
      var source = arguments[index];
      if (source != null) {
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
    }
    return target;
  };
}

// 如果想拷贝访问器(accessor),可使用如下方法
function completeAssign(target, ...sources) {
  sources.forEach(source => {
    let descriptors = Object.keys(source).reduce((descriptors, key) => {
      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
      return descriptors;
    }, {});

    // Object.assign 默认也会拷贝可枚举的Symbols
    Object.getOwnPropertySymbols(source).forEach(sym => {
      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
      if (descriptor.enumerable) {
        descriptors[sym] = descriptor;
      }
    });
    Object.defineProperties(target, descriptors);
  });
  return target;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

# Object.create

// Reference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create
if (typeof Object.create !== 'function') {
  Object.create = function(proto, propertiesObject) {
    if (typeof proto !== 'object' && typeof proto !== 'function') {
      throw new TypeError(
        'Object prototype may only be an Object: ' + proto
      );
    } else if (proto === null) {
      throw new Error(
        'This browser\'s implementation of Object.create is a shim and doesn\'t support \'null\' as the first argument.'
      );
    }

    if (typeof propertiesObject != 'undefined')
      throw new Error(
        'This browser\'s implementation of Object.create is a shim and doesn\'t support a second argument.'
      );

    function F() {}
    F.prototype = proto;

    return new F();
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
本站总访问量    次