Object.prototype 的构造函数 [英] The constructor of Object.prototype

查看:63
本文介绍了Object.prototype 的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中,每个对象都从特定原型继承其属性和方法,其中原型就是对象.

继承形成了一个原型链,其中 (Object.prototype) 位于其顶部(其后是 null,它没有属性或方法)并且所有对象都从它继承(除非其他人向原型链插入其他更改).

如果(Object.prototype)是一个对象,它的构造函数是什么?

我的意思是什么完成这个表达式才能被评估为真.

Object.prototype instanceof .....

解决方案

来自 "this and Object Prototypes" 本书,属于 Kyle Simpsion 的你不懂 JS" 系列

function Foo() {//...}Foo.prototype.constructor === Foo;//真的var a = new Foo();a.constructor === Foo;//真的

<块引用>

Foo.prototype 对象默认(在第 1 行的声明时间)片段!)获得一个公共的、不可枚举的(见第 3 章)属性称为 .constructor,该属性是对对象关联的函数(在本例中为 Foo ).此外,我们看到由构造函数"调用 new Foo() 创建的对象 a 似乎也有一个名为 .constructor 的属性哪一个同样指向创建它的函数".

注意:这实际上不是真的.a 没有 .constructor 属性,尽管 a.constructor 实际上解析为 Foo 函数,构造函数"实际上并不意味着被构造",因为它出现.我们将很快解释这种奇怪之处.

...

"JavaScript 中的对象有一个内部属性,用规范为 [[Prototype]],它只是对另一个的引用对象.".

所以,Object.prototype 本身并不是一个对象.至于你关于 instanceof 的具体问题:

var a = new Function();a.prototype instanceof Object;//真的var b = new String();b. 原型实例对象;//错误的

In JavaScript, every object inherits its properties and methods from a specific prototype, where prototypes are objects.

The inheritance forms a prototype chain where (Object.prototype) stands at its top (followed by null which has no properties or methods) and all the objects inherit from it (unless someone else inserts other changes to the prototype chain).

If (Object.prototype) is an object, what is its constructor?

I mean what completes this expression in order to be evaluated to true.

Object.prototype instanceof .....

解决方案

From "this and Object Prototypes" book of "You don't know JS" series by Kyle Simpsion

function Foo() {
    // ...
}

Foo.prototype.constructor === Foo; // true

var a = new Foo();
a.constructor === Foo; // true

The Foo.prototype object by default (at declaration time on line 1 of the snippet!) gets a public, non-enumerable (see Chapter 3) property called .constructor, and this property is a reference back to the function (Foo in this case) that the object is associated with. Moreover, we see that object a created by the "constructor" call new Foo() seems to also have a property on it called .constructor which similarly points to "the function which created it".

Note: This is not actually true. a has no .constructor property on it, and though a.constructor does in fact resolve to the Foo function, "constructor" does not actually mean "was constructed by", as it appears. We'll explain this strangeness shortly.

...

"Objects in JavaScript have an internal property, denoted in the specification as [[Prototype]], which is simply a reference to another object.".

So, Object.prototype itself is not an object. As to your specific question about instanceof:

var a = new Function();
a.prototype instanceof Object; //true
var b = new String();
b.prototype instanceof Object; //false

这篇关于Object.prototype 的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆