原生js对象合并对象拷贝Object.assign()方法的es5、es6实现

实现思路:支持es6的浏览器,可以直接用Object.assign()合并对象,只支持es5的浏览器,我们用pollyfill的方法。

作用

Object.assign() 方法用于把一个或多个源对象的可枚举属性值复制到目标对象中,返回值为目标对象。

语法

Object.assign(target, ...sources)

参数

target: 目标对象
sources: 源对象

返回值

目标对象

描述

Object.assign 方法只复制源对象中可枚举的属性和对象自身的属性。它在源对象上使用 [[Get]], 在目标对象上使用 [[Set]], 会调用 getter 和 setter。它不适合用于把一个包含 getter 的对象属性合并到一个原型中。如果要把属性定义连同可枚举性复制到一个原型中,应该使用 Object.getOwnPropertyDescriptor() 和 Object.defineProperty() 方法。

String 和 Symbol 类型的属性都会被复制。

当发生错误时,例如有一个属性是不可写的,将会抛出一个 TypeError 错误,目标对象保持不变。

注意 Object.assign() 源对象为 null 或 undefined 时不会报错。

jian示例

克隆对象

var obj = {a: 1};
var copy = Object.assign({}, obj);
console.log(copy); // {a: 1};

合并对象

var o1 = {a: 1};
var o2 = {b: 2};
var o3 = {c: 3};

var obj = Object.assign(o1, o2, o3);
console.log(obj); //{a: 1, b: 2, c: 3}
console.log(o1); //{a: 1, b: 2, c: 3}, 目标对象被改变了

ES5版本实现方法

/**
     * 对象合并polyfill
     * */
    function zyEs6AssignPolyfill() {
        if (!Object.assign) {
            Object.defineProperty(Object, "assign", {
                enumerable: false,
                configurable: true,
                writable: true,
                value: function (target, firstSource) {
                    "use strict";
                    if (target === undefined || target === null)
                        throw new TypeError("Cannot convert first argument to object");
                    var to = Object(target);
                    for (var i = 1; i < arguments.length; i++) {
                        var nextSource = arguments[i];
                        if (nextSource === undefined || nextSource === null) continue;
                        var keysArray = Object.keys(Object(nextSource));
                        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
                            var nextKey = keysArray[nextIndex];
                            var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
                            if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
                        }
                    }
                    return to;
                }
            });
        }
    }
参考文献:http://www.cnblogs.com/heiye168/p/5689006.html

猜你喜欢

转载自blog.csdn.net/fairyier/article/details/80226982