纯原生仿ES6的Object.assign,实现深度合并对象

Posted 新生帝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了纯原生仿ES6的Object.assign,实现深度合并对象相关的知识,希望对你有一定的参考价值。

源码:

function isObj(x){	
	var type = typeof x;
	return x !== null && (type === ‘object‘ || type === ‘function‘);
}

var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError(‘Cannot convert undefined or null to object‘);
	}

	return Object(val);
}

function assignKey(to, from, key) {
	var val = from[key];

	if (val === undefined || val === null) {
		return;
	}

	if (hasOwnProperty.call(to, key)) {
		if (to[key] === undefined || to[key] === null) {
			throw new TypeError(‘Cannot convert undefined or null to object (‘ + key + ‘)‘);
		}
	}

	if (!hasOwnProperty.call(to, key) || !isObj(val)) {
		to[key] = val;
	} else {
		to[key] = assign(Object(to[key]), from[key]);
	}
}

function assign(to, from) {
	if (to === from) {
		return to;
	}

	from = Object(from);

	for (var key in from) {
		if (hasOwnProperty.call(from, key)) {
			assignKey(to, from, key);
		}
	}

	if (Object.getOwnPropertySymbols) {
		var symbols = Object.getOwnPropertySymbols(from);

		for (var i = 0; i < symbols.length; i++) {
			if (propIsEnumerable.call(from, symbols[i])) {
				assignKey(to, from, symbols[i]);
			}
		}
	}

	return to;
}

function deepAssign(target) {
	target = toObject(target);

	for (var s = 1; s < arguments.length; s++) {
		assign(target, arguments[s]);
	}

	return target;
};

  

调用:

deepAssign({a: {b: 0}}, {a: {b: 1, c: 2}}, {a: {c: 3}});
//=> {a: {b: 1, c: 3}}

  

以上是关于纯原生仿ES6的Object.assign,实现深度合并对象的主要内容,如果未能解决你的问题,请参考以下文章

浅拷贝深拷贝

浅拷贝和深拷贝

深拷贝 与浅拷贝理解与实现

经典前端面试题: Object.assign 是浅拷贝还是深拷贝?实现深拷贝的方法有哪些?

#yyds干货盘点#Object.assign实现的是浅拷贝还是深拷贝?

JS 原生方法原理探究如何实现浅拷贝和深拷贝?