My Octopress Blog

A blogging framework for hackers.

Javascript中的继承

| Comments

javascript中的继承主要是通过原型链prototype来实现

1.原型链继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function SuperType(){
    this.supername = "father";
}

SuperType.prototype.sayHello = function(){
    console.log(this.supername);
}

function SubType(){
    this.subname = "son";
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;

var sub = new SubType();
sub.sayHello();//father

使用原型链继承的主要问题就是共享,字类会共享父类所有的属性以及方法,而有时候我们不希望子类共享属性.示例代码如下:

1
2
3
4
var sub = new SubType();
var sub1 = new SubType();
sub1.supername = "sub1 change the father";
sub.sayHello();//sub1 change the father

可以通过下面的介绍的继承方法解决这个问题

2.组合继承

组合继承就是使用构造函数和原型链共同实现继承,通过调用超类的构造函数来实现实例属性的不共享,通过原型链实现共享超类的访求.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function SuperType(){
    this.supername = "father";
}

SuperType.prototype.sayHello = function(){
    console.log(this.supername);
}

function SubType(){
    SuperType.call(this)
    this.subname = "son";
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;

var sub = new SubType();
sub.sayHello();//father
var sub1 = new SubType();
sub1.supername = "sub1 change the supername";
sub.sayHello();//father
sub1.sayHello();//sub1 change the supername

使用组合继承还有一个优势就是能向父类传参

1
2
3
4
5
6
7
8
9
function SuperType(name){
    this.supername = name;
}
function SubType(){
    SuperType.call(this, "jack")
    this.subname = "son";
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;

3. 原型式继承

1
2
3
4
5
6
7
8
9
10
11
12
function object(o){
    function F() {}
    F.prototype = o;
    return new F();
}

var person = {
    name: "jack",
    friends: ['rose']
}

var anotherperson = object(person);

这种方式的基本思路是通过已有对象来创建一个实例,但是所有实例都会共享属性

4.寄生式继承

寄生式继承是基于原型式继承

1
2
3
4
5
6
7
8
9
function createAnother(original) {
    var clone = object(original);
    clone.sayHi = function() {
        console.log("Hi");
    }
}

var another = createAnother(person);
another.sayHi(); //Hi

5.寄生组合继承

寄生组合继承主要是解决组合继承方式中父类会被实例化两次的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function inheritance(subType, superType) {
    var clone = object(superType.prototype);
    clone.constructor = subType;
    subType.prototype = clone;
}

function SuperType(){
    this.supername = "father";
}

SuperType.prototype.sayHello = function(){
    console.log(this.supername);
}

function SubType(){
    SuperType.call(this)
    this.subname = "son";
}

inheritance(SubType, SuperType);

Comments