Javascript:“ Object.setPrototypeOfChild.prototype,Parent.prototype”与“ Child.prototype = Object.createParent.prototype”

问题描述

例如,在这段非常原始和简化的代码中:

function Parent() { }
function Child() { }
Object.setPrototypeOf(Child.prototype,Parent.prototype); // OR: "Child.prototype.__proto__ = Parent.prototype;" (the result is totally identical)

与之相对:

function Parent() { }
function Child() { }
Child.prototype = Object.create(Parent.prototype);

然后我按照以下方式检查这两段代码

console.log(child instanceof Child); // true for both examples
console.log(child instanceof Parent); // true for both examples
console.log(Parent.prototype.isPrototypeOf(child)); // true for both examples
console.log(Child.prototype.isPrototypeOf(child)); // true for both examples

但是:对接下来的两行进行检查会得出不同的结果-

console.log(JSON.stringify(Object.getownPropertyNames(Child.prototype),null,2)); // ["constructor"] vs []
console.log(child.__proto__); // a constructor property is shown (on the first place) only in the first case and no constructor property – in the second case

-仅在第一种情况下显示“父”构造函数(请参见所附图像)。 是什么原因导致这种差异?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)