---
title: "javascript的构造函数"
author: "tyny"
date: "2012-09-20T22:37:47Z"
tags: ["JavaScript"]
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2012-09-20T22:37:47Z"
id: 1682622
url: "https://tyny.iteye.com/blog/1682622"
---

本来打算翻译这篇文章，但是感觉原文才是真正原汁原味的，所以这里也偷偷懒。

之前一直纠结于对象的构造函数，通过阅读Joost Diepenmaat的这篇【Constructors considered mildly confusing】，有了比较明晰的了解。一般来说，对象的constructor其实就是对象的\[\[Prototype]]的构造函数。

例如函数

```
function A() {}
function B() {}
function C() {}
B.prototype = new A();
C.prototype = new B();
var c = new C();
console.log(c.constructor === A );    //true
```

 

那么c.constructor是什么呢。c.constructor==C.prototype.constructor==B.prototype.constructor==A.prototype.constructor==A，即是函数A。因为c.constructor等于函数C的原型的构造函数，C函数的原型是什么呢——B的对象，B的对象的构造函数是函数B的原型的构造函数，B的原型同样是——函数A的对象，A的对象的构造函数就是函数A。这就是为啥c.constructor 等于 A(需要注意的是，这是新建C时的状况，即使后面修改了部分构造函数的原型，这里的原型链依然是新建C那个时刻的原型链)。

对于instanceof，这个函数的作用不用多说，但是他的实际含义确实很模糊（可能自己的理解不全），这篇文章同样也做了同样的说明，其实他就是检测比较对象的原型链中是否存在比较构造函数的原型。详细请参照【Constructors considered mildly confusing】

题外话，最后发现[Mozilla Developer Network](https://developer.mozilla.org/en-US/) 的文章相当不错，感觉有时候比一些书籍更为详细。

引用

 

- [Constructors considered mildly confusing](http://joost.zeekat.nl/constructors-considered-mildly-confusing.html "Constructors considered mildly confusing")
- [JavaScript inheritance and the constructor property](http://stackoverflow.com/questions/8093057/javascript-inheritance-and-the-constructor-property "JavaScript inheritance and the constructor property")
- [Details of the object model](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Details_of_the_Object_Model "Details of the object model")