Object.create实现类继承和克隆对象

Object.create实现类继承

先看不用Object.create来实现继承

function Pd(){
}
Pd.prototype = Array.prototype;
Pd.prototype.constructor = Pd;
var pdd = new Pd();
pdd.push(3);
console.log(pdd); // Pd [3] __proto__:Array(0)直接就是真正的数组的__proto__

效果:

image.png

用Object.create实现继承

function Pd(){
}
Pd.prototype = Object.create(Array.prototype);
Pd.prototype.constructor = Pd;
var pdd = new Pd();
pdd.push(3);
console.log(pdd); // Pd [3] __proto__:Array[__proto__:Array(0)]就是__proto__里面包含真正的数组的__proto__

效果:

image.png

区别

写法

Pd.prototype = Array.prototype;Pd.prototype = Object.create(Array.prototype);

返回值

  • Pd [3] __proto__:Array(0)直接就是真正的数组的__proto__;
  • Pd [3] __proto__:Array[__proto__:Array(0)]就是__proto__里面包含真正的数组的__proto__

用Object.create克隆对象

var obj1 = {a:2,b:{name:'小明'}};
var obj2 = Object.create(obj1);
console.log(obj2); // {}
obj2.a = 3;
obj2.b.name = '小红';
console.log(obj1); // {a:2,b:{name:'小红'}};

结论:obj1对象中的一级对象a:2并没有受影响,但二级对象b已经受影响。所以Object.create克隆的对象也只能实现一级对象的深拷贝。

obj2的具体值:

image.png

原文地址:https://www.cnblogs.com/firefly-pengdan/p/13383986.html