Javascript::为什么 Object.hasOwnProperty ('caller' ) 返回 true?

标签 javascript inheritance

Object 继承自 Function.prototype,而 Function.prototype 又继承自 Object.prototype。

这是因为在内部,Object实际上是一个函数

function Object(){[native code]}

这就是为什么我们可以写这样的代码

var ob=new Object();

对象从 Function.prototype 继承了诸如 'caller' 、 'arity' 等属性

但是(这就是令人困惑的地方)

alert(Object.hasOwnProperty('caller')); //returns TRUE ! surprising

它不应该返回 false 因为 Object 实际上从 Function.prototype 继承了“caller”属性吗?

同理

alert(Function.hasOwnProperty('caller')); 
/*returns True. expected 'false' as Function object has no property of its own and inherits everything from Function.prototype*/

alert(Number.hasOwnProperty('caller')); //again returns true, unexpectedly

那么,有人知道为什么会这样吗?

非常感谢。我希望我听起来不幼稚

编辑

尝试 Object.getOwnPropertyNames(Object) 确实返回了 'caller' 作为直接在 Object 本身上的属性。 所以 Object.hasOwnProperty('caller') 实际上是正确的

但是,现在的问题是为什么在 MDN 文档中提到 'caller' 是从 Function 继承的。 所以它肯定会导致困惑。

那么这是文档中的一些错误吗? 谢谢。

EDIT-2

我能得出对象有自己的结论吗

caller, length 等属性 甚至 Object.lengthObject.__proto__.length 是不一样的。如果 Object 确实从其 [[prototype]] 继承了 length 属性,它应该是相等的,即 Function.prototype 但事实并非如此

问题是为什么 MDN 提到 Object 只是从其 [[prototype 继承了 callerlengtharity 等]] 对象 ?恕我直言,这有点误导

最佳答案

来自 MDN :

A function created with a function declaration is a Function object and has all the properties, methods and behavior of Function objects.

在严格模式下,每个函数都有自己的 callerarguments 属性。请参阅 ES5 规范 15.3.513.2 .

Function instances that correspond to strict mode functions (13.2) and function instances created using the Function.prototype.bind method (15.3.4.5) have properties named “caller” and “arguments” that throw a TypeError exception.

关于Javascript::为什么 Object.hasOwnProperty ('caller' ) 返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27143646/

相关文章:

javascript - Vuetify 在数据表单元格内使用 v-html

javascript - 使用内部页面引用隐藏/取消隐藏 HTML 中的元素

javascript - 有没有办法在 Svelte 中将 props 声明为可选

java - 在接口(interface)继承中使用 Java 泛型进行代码重用

c# - 表单类,在简单的代码测试中不断得到 "System.StackOverflowException"

C++判断类是否可以使用对象-文字RPG游戏

javascript - backbone.js 查看事件处理

javascript - 从 html 表单调用带参数的 JavaScript 函数

Typescript 类扩展了 Tuple

inheritance - Scala函数的方差和覆盖