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.length
和 Object.__proto__.length
是不一样的。如果 Object 确实从其 [[prototype]]
继承了 length 属性,它应该是相等的,即 Function.prototype
但事实并非如此
问题是为什么 MDN 提到 Object 只是从其 [[prototype 继承了
对象 ?恕我直言,这有点误导caller
、length
、arity
等]]
最佳答案
来自 MDN :
A function created with a function declaration is a Function object and has all the properties, methods and behavior of Function objects.
在严格模式下,每个函数都有自己的 caller
和 arguments
属性。请参阅 ES5 规范 15.3.5和 13.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/