---
title: "借用构造函数继承"
author: "MirrorAvatar"
date: "2015-03-11T22:25:04Z"
tags: ["JavaScript"]
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2015-03-11T22:25:48Z"
id: 2191630
url: "https://mirroravatar.iteye.com/blog/2191630"
---

## 基本概念

借用构造函数（constructor stealing）进行继承的基本思想就是：**在子类型构造函数的内部调用超类型构造函数**。

那么，如何调用？函数只不过是在特定环境中执行代码的对象，因此通过使用apply()和call()方法也可以在（将来）新创建的对象上执行构造函数。

## [](https://github.com/MirrorAvatar/Blog/blob/gh-pages/_posts/2015-03-11-%E5%80%9F%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E7%BB%A7%E6%89%BF.md#%E7%A4%BA%E4%BE%8B%E4%BB%A3%E7%A0%81)示例代码

```
function SuperType() {
    this.number = [1, 2, 3];
}

function SubType() {
    SuperType.call(this);
}

var instance1 = new SubType();
instance1.number.push(4);
instance1.number;  // "1,2,3,4"

var instance2 = new SubType();
instance2.number;  // "1,2,3"
```

```
 
```

## [](https://github.com/MirrorAvatar/Blog/blob/gh-pages/_posts/2015-03-11-%E5%80%9F%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E7%BB%A7%E6%89%BF.md#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E7%BB%A7%E6%89%BF%E7%9A%84%E4%BC%98%E5%8A%BF%E5%8F%AF%E4%BB%A5%E4%BC%A0%E9%80%92%E5%8F%82%E6%95%B0)构造函数继承的优势：可以传递参数

```
function SuperType(name) {
    this.name = name;
}

function SubType() {
    Super.call(this, "MirrorAvatar");
    this.age = 3;
}

var instance = new SuperType();

instance.name;  //MirrorAvatar
instance.age;  //3
```

```
 
```

## [](https://github.com/MirrorAvatar/Blog/blob/gh-pages/_posts/2015-03-11-%E5%80%9F%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E7%BB%A7%E6%89%BF.md#%E5%80%9F%E7%94%A8%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E7%BB%A7%E6%89%BF%E7%9A%84%E9%97%AE%E9%A2%98)借用构造函数继承的问题

1. 方法都在构造函数中定义，函数无复用性；
2. 在超类型的原型中定义的方法，对子类型而言也是不可见的，结果所有类型都只能使用构造函数模式。

以上，构造函数的技术很少单独使用。