浅克隆:只能克隆原始对象自身的值,不能克隆它继承的值
方法一:
function clone(origin) { return Object.assign({}, origin); }
方法二:
function clone(origin) { return JSON.parse(JSON.stringify(origin)) }
深克隆:克隆对象自身的值和集成的值
方法一:
function clone(origin) { let originProto = Object.getPrototypeOf(origin); return Object.assign(Object.create(originProto), origin); }
方法二:
function clone(obj){ return Object.create( Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj) ) }
方法三: __proto__ 属性在非浏览器环境不一定部署,早期的IE肯定也没有
function clone(obj){ return { __proto__: Object.getPrototypeOf(obj), ...obj }; }
Object.assign
方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target),不包含原型
Object.assign(target, source1, source2);
_proto__
属性(前后各两个下划线),用来读取或设置当前对象的prototype
对象
Object.create()
方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
// es6 的写法 const obj = { method: function() { ... } }; obj.__proto__ = someOtherObj; // es5 的写法 var obj = Object.create(someOtherObj); obj.method = function() { ... };
Object.setPrototypeOf()
方法的作用与__proto__
相同,用来设置一个对象的prototype
对象,返回参数对象本身。它是 ES6 正式推荐的设置原型对象的方法
Object.getPrototypeOf()该方法与Object.setPrototypeOf
方法配套,用于读取一个对象的原型对象。
Object.getOwnPropertyDescriptors()
方法,返回指定对象所有自身属性(非继承属性)的描述对象。