---
title: "javascript的继承机制"
author: "water84222"
date: "2012-04-11T17:08:50Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2012-04-11T17:19:57Z"
id: 1483491
url: "https://onlyLove.iteye.com/blog/1483491"
---

转载于：[http://www.iteye.com/topic/437567](http://www.iteye.com/topic/437567)

 

测试javascript的继承机制，首先，要理解什么叫继承：继承主要是指子类拥有父类开放的属性及方法，其实javascript是不包含继承这种机制的，但是在现在这个面向对象充斥着开发人员的开发的时候，难免javascript也要模拟这样的一种写吧，尽量满足大部份开发人员的开发习惯，下面请看javascript是如何实现这些继承体系的。

1.先定义一个父类Person

Js代码      [![收藏代码](http://www.iteye.com/images/icon_star.png)](http://www.iteye.com/topic/437567 "收藏这段代码")

1. function Person(name, sex) {
2. this.name = name;
3. this.sex = sex;
4. this.move = function() {
5. alert("move");
6. };
7. }

2.对象冒充  
可以冒充得到正确结果，其实javascript是这样的，将整个方法替换掉pe，当我们调用this.(name,sex);时相当于在Man里面执行上面的那一段代码，而此时的this已经代表的是Man对象，使Man也具有了name，sex等属性与及move方法。

 

Js代码      [![收藏代码](http://www.iteye.com/images/icon_star.png)](http://www.iteye.com/topic/437567 "收藏这段代码")

01. function Man(name, sex, address, phone) {
02. this.pe = Person;
03. this.pe(name, sex);
04. delete this.pe;
05. this.address = address;
06. this.phone = phone;
07. }
08. function Woman(name, sex, birthday) {
09. this.pe = Person;
10. this.pe(name, sex);
11. delete this.pe;
12. this.birthday = birthday;
13. }

 

3.call 方法实现继承，call方法里面会将this及Person中的参数传递到调用的方法中，此时的this代表的是Man2对象，当调用到Person的构造方法的时候，调用this.name的时候已经是Man2.name了，这种方法也可以实现继承。

Js代码      [![收藏代码](http://www.iteye.com/images/icon_star.png)](http://www.iteye.com/topic/437567 "收藏这段代码")

1. function Man2(name, sex, address, phone) {
2. Person.call(this, name, sex);
3. this.address = address;
4. this.phone = phone;
5. }

 

4.apply 方法实现继承，其实apply方法和call方法是一样，只不过apply传递过去的参数要用一个数据包装起来而已。

 

Js代码      [![收藏代码](http://www.iteye.com/images/icon_star.png)](http://www.iteye.com/topic/437567 "收藏这段代码")

1. function Man3(name, sex, address, phone) {
2. Person.apply(this, new Array(name, sex));
3. this.address = address;
4. this.phone = phone;
5. }

 

5.若父类中有通过prototype定义的方法或者属性，上述的三种方法无法实现继承。

原型链的缺点是不支持多继承。

原型prototype链如下：

 

Js代码      [![收藏代码](http://www.iteye.com/images/icon_star.png)](http://www.iteye.com/topic/437567 "收藏这段代码")

01. function Person2() {
02. }
03. Person2.prototype.name = "";
04. Person2.prototype.sex = "";
05. Person2.prototype.move = function() {
06. alert(this.name);
07. };
08. function Man4() {
09. }
10. Man4.prototype = new Person2();

 

5.混合方式，通过混合方式，可以达到最大的重用。  
function Person3(name, sex) {  
    this.name = name;  
    this.sex = sex;  
}

Person3.prototype.login = function() {  
    alert("prototype constructual");  
};

function Man5(name, sex, birthday) {  
    Person3.call(this, name, sex);  
    this.birthday = birthday;  
}

Man5.prototype = new Person3();

Man5.prototype.say = function() {  
    alert("say hello!");  
};

 

Man5.prototype.say();

Man5.prototype.login();