childObj.prototype = Object.create(parentObj.prototype) 和 ch

What's the difference between childObj.prototype = Object.create(parentObj.prototype) and childObj.prototype = parentObj.prototype?

本文关键字:prototype ch parentObj create Object childObj      更新时间:2023-09-26

我想知道两者之间的区别:

childObj.prototype = Object.create(parentObj.prototype)

childObj.prototype = parentObj.prototype;

因为它们都需要在子对象中调用父构造函数才能访问构造函数属性。

我知道 Object.create 函数是如何工作的,我注意到区别只是因为它返回了一个带有父原型的新对象。我想我不理解的是返回带有父原型的新对象的效果。

您的第一个示例是正确的方法,因为它创建了一个以parentObj.prototype[[Prototype]]的新对象:

childObj.prototype = Object.create(parentObj.prototype); // { __proto__: parentObj.prototype }

第二个只是将childObj.prototype设置为与parentObj.prototype相同的对象。这会导致一些问题:

function parentObj() {
}
parentObj.prototype.parentFn = function() { console.log('parent'); };

function childObj() {
}
childObj.prototype = parentObj.prototype;
// here we are writing onto parentObj.prototype as well!!!
childObj.prototype.childFn = function() { console.log('child'); };
var child = new childObj();
var parent = new childObj();
child.parentFn(); // 'parent'
parent.childFn(); // 'child' --- this should not happen!!!

在直接分配对象时,我们已经写入了父.prototype

基本上Object.create的第一个参数是原型,第二个参数是属性描述符对象。因此,当您将原型对象单独传递给Object.create时,将创建一个没有任何自身属性的对象,并且传递的对象将被分配给新创建对象的__proto__

var x = {a:10};
var y = Object.create(x);
console.log(y); //{__proto__:{a:10}}

但是,当您将父项的原型分配给子项的原型时,只是引用是重叠的。并且对象不会发生任何结构变化。

我能想到的一个区别是:
假设你有

c = new childObj()
p = new parentObj()

在这两种情况下,您都将拥有

c instanceof parentObj === true

但在第二种情况下,您还将拥有

p instanceof childObj === true

在第一种情况下,您将拥有

p instanceof childObj === false