---
title: "js继承---原型链"
author: "小丑鱼0703"
date: "2015-04-20T14:45:44Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2015-04-20T14:45:44Z"
id: 2201942
url: "https://wangjingyi.iteye.com/blog/2201942"
---

原型链方式

    默认继承机制，将需要重用的属性和方法迁移至原型对象中，而将不可重用的部分设置为对象的自身属性，但这种继承方式需要新建一个实例作为原型对象，效率上会低一些。

```js
function Shape() {
    this.name = '形状';
}
Shape.prototype.perimeter = function() { };

function Square() {
    this.length = 1;
}
// Javascript中没有抽象类的概念，所以Shape是可以实例化的
// 子对象构造函数的prototype属性指向父对象的一个实例
Square.prototype = new Shape();
// Square的prototype属性被重写了，指向了一个新对象，但是这个新对象的constructor属性却没有正确指向Square，JS 引擎并不会自动完成这件工作，需要手动去将Square的原型对象的constructor属性重新指向Square
Square.prototype.constructor = Square;
Square.prototype.perimeter = function() {
    return this.length * 4;
};
var square = new Square();
square.name; // '形状'
square.perimeter(); // 4
```