---
title: "JavaScript类和继承：constructor属性"
author: "xwpxcom"
date: "2011-01-15T17:02:41Z"
tags: ["JavaScript", "prototype"]
categories: ["Web前端"]
slug: "javascript-constructor"
draft: false
lastmod: "2011-01-15T17:02:41Z"
id: 875348
url: "https://xwpxcom.iteye.com/blog/875348"
---

constructor属性始终指向创建当前对象的构造函数。比如下面例子：

01. // 等价于 var foo = new Array(1, 56, 34, 12);
02. var arr = \[1, 56, 34, 12];
03. console.log(arr.constructor === Array); // true
04. // 等价于 var foo = new Function();
05. var Foo = function() { };
06. console.log(Foo.constructor === Function); // true
07. // 由构造函数实例化一个obj对象
08. var obj = new Foo();
09. console.log(obj.constructor === Foo); // true
10. // 将上面两段代码合起来，就得到下面的结论
11. console.log(obj.constructor.constructor === Function); // true

*复制代码*

但是当constructor遇到prototype时，有趣的事情就发生了。

我们知道每个函数都有一个默认的属性prototype，而这个prototype的constructor默认指向这个函数。如下例所示：

01. function Person(name) {
02. this.name = name;
03. };
04. Person.prototype.getName = function() {
05. return this.name;
06. };
07. var p = new Person("ZhangSan");
08. console.log(p.constructor === Person); // true
09. console.log(Person.prototype.constructor === Person); // true
10. // 将上两行代码合并就得到如下结果
11. console.log(p.constructor.prototype.constructor === Person); // true

*复制代码*

当时当我们重新定义函数的prototype时（注意：和上例的区别，这里不是修改而是覆盖），constructor属性的行为就有点奇怪了，如下示例：

01. function Person(name) {
02. this.name = name;
03. };
04. Person.prototype = {
05. getName: function() {
06. return this.name;
07. }
08. };
09. var p = new Person("ZhangSan");
10. console.log(p.constructor === Person); // false
11. console.log(Person.prototype.constructor === Person); // false
12. console.log(p.constructor.prototype.constructor === Person); // false

为什么呢？

原来是因为覆盖Person.prototype时，等价于进行如下代码操作：

1. Person.prototype = new Object({
2. getName: function() {
3. return this.name;
4. }
5. });

而constructor属性始终指向创建自身的构造函数，所以此时Person.prototype.constructor === Object，即是：

01. function Person(name) {
02. this.name = name;
03. };
04. Person.prototype = {
05. getName: function() {
06. return this.name;
07. }
08. };
09. var p = new Person("ZhangSan");
10. console.log(p.constructor === Object); // true
11. console.log(Person.prototype.constructor === Object); // true
12. console.log(p.constructor.prototype.constructor === Object); // true

怎么修正这种问题 呢？方法也很简单，重新覆盖Person.prototype.constructor即可：

01. function Person(name) {
02. this.name = name;
03. };
04. Person.prototype = new Object({
05. getName: function() {
06. return this.name;
07. }
08. });
09. Person.prototype.constructor = Person;
10. var p = new Person("ZhangSan");
11. console.log(p.constructor === Person); // true
12. console.log(Person.prototype.constructor === Person); // true
13. console.log(p.constructor.prototype.constructor === Person); // true