javascript之继承

阮一峰的讲解

构造函数继承

function Animal() {
    this.species = "动物";
}

function Cat(name,color) {
    this.name = name;
    this.color = color;
}

构造函数绑定

function Cat(name,color) {
    Animal.apply(this,arguments);
    this.name = name;
    this.color = color;
}

var cat1 = new Cat("大毛","黄色");
alert(cat1.species); //动物

prototype模式

Cat.prototype = new Animal(); 
//Cat.prototype.constructor === Animal;
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛","黄色");
alert(cat1.species); //动物

PS:如果替换了prototype,都要为新的prototype对象加上constructor属性,并将这个属性指向原来的对象。

直接继承prototype

function Animal(){}
Animal.prototype.species = "动物";

Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;

与前一种方法相比,由于不用执行和建立Animal的实例了,比较省内存
缺点:Animal.prototype.constructor === Cat

利用空对象作为中介

var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

F是空对象,几乎不占内存

拷贝继承

function Animal(){}
Animal.prototype.species = "动物";

function extend(Child,Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for(var i in p){
        c[i] = p[i];
    }
}

非构造函数的继承

var  Chinese = {
    nation: '中国'
};
var Doctor = {
    career: '医生'
}

两个对象都是普通对象,不是构造函数,无法使用构造函数方法实现继承

object()方法

function object(o){
    function F(){};
    F.prototype = o;
    return new F();
}把子对象的prototype属性指向父对象

var Doctor = object(Chinese);
Doctor.career = '医生';
alert(Doctor.nation); // 中国

浅拷贝

function extend(p) {
    var c = {};
    for(var i in p){
        c[i] = p[i];
    }
    return c;
}

浅拷贝只能拷贝基本类型的数据

深拷贝

能够实现数组和对象的拷贝

function deepCopy(p,c){
    var c = c || {};
    for(var i in p){
        if(typeof p[i] === 'Object'){
            c[i] = (p[i].constructor === 'Array')? [] : {};
            deepCopy(p[i],c[i]);
        }else{
            c[i] = p[i];
        }
    }
    return c;
}

你可能感兴趣的:(继承,javascript)