首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么函数的原型是函数,为什么对象是从那里继承的?

为什么函数的原型是函数,为什么对象是从那里继承的?
EN

Stack Overflow用户
提问于 2013-07-27 08:41:59
回答 1查看 274关注 0票数 1
代码语言:javascript
复制
Function.prototype // function Empty() {}

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

在那之后,Object.__proto__ == Function.prototype又有什么意义呢?对象应该是最高的对象,当Function.prototype从.继承时,它是如何从Function继承的。Object.prototype

代码语言:javascript
复制
Object instanceof Function // true
Function instanceof Object // of course true
Function instanceof Function // true
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-27 09:14:25

米克洛斯是对的,但更简单地说:

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

换句话说

代码语言:javascript
复制
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

代码语言:javascript
复制
// This means that Everything that inherits from function will
console.log(`Function.prototype`) === function Empty() {}

又一次扭转

代码语言:javascript
复制
// 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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17895940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档