0

我可能不会像我应该的那样阅读 chromes 对象显示:

我有这个代码:

function Foo(){};
var g= new Foo();

另外 - (控制台代码):

>>Foo.prototype //  Foo {}

问题 :

它是否说它的类型是实例Foo?还是只是一个plain普通的对象?

ps - 我听说原型是一个常规对象。所以 Foo 这个词Foo{} 让我觉得它是一个例子Foo

我为什么要问?

因为运行这个:

Foo.prototype.__proto__

显示Object {}而不是它的实例构造函数原型,它是:Foo.prototype...

附加信息 :

我的相关问题(没有谈到 chrome 显示对象的方式

4

1 回答 1

3

Foo.prototype has a property constructor, which is defined as Foo.prototype.constructor = Foo; and that's why the console shows it like that

That's the consequence of Foo.prototype having a constructor property. Each prototype of a constructor function has a constructor property which points back to that function, e.g.

Foo.prototype.constructor = Foo;

Now, it looks like in order to determine which constructor function an object is an instance of, Chrome's console looks at the constructor property of an object and then assumes that the object is an instance of that function.
This works in almost all cases, but not for prototype objects, because they have explicitly set a constructor property.

Example:

> function Foo() {}
undefined
> Foo.prototype.constructor = function xyz() {}
function xyz() {}
> Foo.prototype
xyz {}

Another, simpler example:

> var obj = {};
> obj
Object {}
> obj.constructor = function xyz() {};
function xyz() {}
> obj
xyz {}

As you can see, the console is really just looking at the constructor property of an object (which is usually inherited) and then prints the function name of the function assigned to it.

Foo.prototype.constructor is just a normal property which is assigned when a function is created. It's purpose is that actual instances of Foo (created with new Foo) have a constructor property which points to Foo. Since instances inherit all properties from the prototype.

于 2013-11-02T18:22:53.353 回答