gpt4 book ai didi

javascript - Object.getPrototypeOf(o) 方法问题

转载 作者:行者123 更新时间:2023-11-28 01:12:04 24 4
gpt4 key购买 nike

我很难理解 Object.getPrototypeOf(o)。我正在下面的代码中使用该方法。

var obj0 = {x: 10};

var obj1 = Object.create(null, {
'name': {value: 'first object name', enumerable: false},
});

var obj2 = Object.create(obj1, {
'location': {value: 'second object location'},
});

alert(Object.getPrototypeOf(obj0)); // [object Object]
alert(Object.getPrototypeOf(obj1)); // null
alert(Object.getPrototypeOf(obj2)); // TypeError: Cannot convert object to primitive value

如果有任何提示,我将不胜感激:

1/为什么object2返回TypeError?

2/Object.getPrototypeOf 方法是否总是返回 [object Object] 作为原型(prototype)链中的“最高对象”?我假设它会给我它是链中“最近”的对象,所以例如。如果存在以 obj0 作为原型(prototype)的 obj3,它会给我 [obj0 Object] 而不是 [object Object]。

最佳答案

这只是使用alert的问题,它将警报对象转换为字符串。 [object Object]{} 的字符串表示形式:

({foo: 'bar'}).toString(); // [object Object]

您应该使用控制台进行测试,这将更好地表示该对象(请参阅 example on JSFiddle )。

示例中还有一个新对象 obj3,它表明 Object.getPrototypeOf() 确实 返回最近的对象,而不是根原型(prototype)。

关于javascript - Object.getPrototypeOf(o) 方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24303696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com