javascript - 为什么Function的原型(prototype)是一个函数,为什么Object继承自函数?

标签 javascript

Function.prototype // function Empty() {}

这有什么意义?例如,如果我们使用 Number 对象,我们可以看到他的原型(prototype) (Number.__proto__) 是 Function.prototype 其中包含方法例如applycall。如果 Number 的原型(prototype)是一个空函数而不是像所有其他原型(prototype)一样的常规原型(prototype)对象,我该如何使用 Number.apply(..) ? (数字原型(prototype)、字符串原型(prototype)、任何其他自定义原型(prototype)都是对象。甚至 Object.prototype 也是对象)。

之后,Object.__proto__ == Function.prototype 有何意义? Object应该是最高的对象,当Function继承自..Object.prototype时,它如何继承Function.prototype!

Object instanceof Function // true
Function instanceof Object // of course true
Function instanceof Function // true

最佳答案

Miklos 是对的,但更简单地说:

Object.__proto__ == Function 意味着 Object 本身是一个函数,因为它是构造函数。这并不意味着继承Object的对象将继承Function。对象继承构造函数的 .prototype,而不是其 .__proto__

换句话说

function Car (){}
inst = new Car ();
// inst inherits from Car.prototype
// inst.__proto__ == Car.prototype;
// Car inherits from Function.prototype because it is a function
// Car.__proto__ == Function.prototype;

但这并不意味着inst继承自Function.prototype,你不能调用applycall 就可以了。

// This means that Everything that inherits from function will
console.log(`Function.prototype`) === function Empty() {}

另一个转折

// This means that the constructor function (Object)
// inherits from `Function.prototype` That is, you can use call and apply,
// And at a lower language level, you can use () and new on it.
Object instanceof Function // true

// It doesn't mean that instances created from Object inherit 
// from Function.prototype (can't use call/apply)
(new Object()) instanceOf Function ? // false
(new Object()).apply === undefined ? // true

// This means that functions themselves are objects, everything is an object
// They have properties like hasOwnProperty and isPrototypeOf
// Not that everything that inherits from Object.prototype will also inherit
// From Function.prototype
Function instanceof Object // of course true

关于javascript - 为什么Function的原型(prototype)是一个函数,为什么Object继承自函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17895940/

相关文章:

javascript - 在类型脚本中添加 SVG 内容时出现错误

javascript - Onmouseout 和 onmouseover 组合无法隐藏和显示图像

javascript - React-router hashHistory 推送仅更改 URL

JavaScript 无法在谷歌浏览器和智能手机浏览器上运行

javascript - PeerJS 文字聊天

javascript - jquery scale scale 函数以指数方式增加大小

javascript - 删除 div 中文本周围的空格

javascript - Win8底部滚动条

javascript - 如何对未注册用户隐藏图像

javascript - 将 jQuery 对象类型转换回未定义