不推荐扩展Object类,所以我尝试扩展一个对象,例如:
var obj = {'a': 1, 'b': 2, 'c': 3};
这里是 object literal {'a': 1, 'b': 2, 'c': 3}
与 new Object({'a': 1, 'b': 2, 'c': 3})
相同。
我试过 obj.prototype = {d: 4}
但它将“原型(prototype)”设置为属性,而不是真正的 prototype .
忘了Object.defineProperties
!
也试过Object.create
: 为什么这不起作用? ...
var ext = Object.create(obj, {'d': { value:4 }});
console.log(obj.isPrototypeOf(ext)) // => true! obj is prototype of ext
console.log(ext); // => {d: 4}
console.log(obj); // => {a: 1, b: 2, c: 3}
Console.log 说 obj.isPrototypeOf(ext) == true
那么为什么 ext
不是 {'a': 1, 'b': 2 , 'c': 3, 'd': 4}
?
如何在不是 Object 类或 Function 的对象实例上制作原型(prototype)?
更新:作为Nicholas Tower 的回答,我错过了 the second parameter 中的可枚举项应该是:{'d': { value:4, enumerable: true }}
我在 Chrome 控制台中遇到箭头下拉问题,我错过了点击查看继承值的机会。我本可以使用 assign()
来“扩展”obj。现在它显示 obj = {'a': 1, 'b': 2, 'c': 3}
__proto__
{d: 4}
没问题。从 OO 的 Angular 来看,这意味着 obj
extends {d: 4}
*。在对象obj上做了一个原型(prototype)。
我接受了 t.888 的回答,它帮助我了解了 console.log
如何显示对象以及扩展现有对象的正确方法。
最佳答案
why is ext not {'a': 1, 'b': 2, 'c': 3, 'd': 4} ?
是的,但是您没有使 d
可枚举,因此 console.log 看不到它。
const obj = {'a': 1, 'b': 2, 'c': 3};
const ext = Object.create(obj, {'d': {
value:4,
enumerable: true // <---- added this
}});
console.log('ext', ext);
for (const key in ext) {
if (ext.hasOwnProperty(key)) {
console.log('own property', key, ext[key]);
} else {
console.log('inherited property', key, ext[key]);
}
}
关于javascript - 如何在不是对象或函数的对象实例上进行原型(prototype)设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56248074/