为什么要改变构造函数? [英] Why is the constructor changed?

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

问题描述

为什么添加原型后构造函数从Foo变成了Object?如何访问原始构造函数?

Why does the constructor change from Foo to Object after adding a prototype? How can I get access to the original constructor?

代码:

function Foo() {}
var foo1 = new Foo();
console.log('foo1: ' + foo1.constructor);

Foo.prototype = {}
var foo2 = new Foo();
console.log('foo2: ' + foo2.constructor);

输出:

foo1: function Foo() {}

foo2: function Object() {
    [native code]
}

http://jsfiddle.net/vDCTJ/

推荐答案

发生这种情况是因为您为 Foo 的原型提供了一个全新的对象,而您没有设置该对象的构造函数"属性.

It happens because you gave Foo a brand new object for its prototype, and you didn't set that object's "constructor" property.

Foo.prototype = { constructor: Foo };

实例化的函数对象为其原型"属性获取一个对象,该对象已经以这种方式初始化.

Instantiated function objects get an object for their "prototype" property that's already initialized that way.

这篇关于为什么要改变构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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