javascript继承的实现

继承模式一、

var Parent = function(name){
    this.name = name || 'parent';
}

Parent.prototype = {
    obj:{a: 1},
    
    getName: function(){
        return this.name;
    }
}

var Child = function(name){
    this.name = name || 'Child';
}

Child.prototype = new Parent()

var p = new Parent();

var c = new Child();

console.log( p.getName() )
console.log( c.getName() )

缺点:子类如果要实现父类构造器里的初始化,需要重写。

模式二、

var Parent = function(name){
    this.name = name || 'parent';
}

Parent.prototype = {
    obj:{a: 1},
    
    getName: function(){
        return this.name;
    }
}

var Child = function(name){
    Parent.apply(this, arguments);  // 改进点
}

Child.prototype = new Parent()

var p = new Parent();

var c = new Child('child');

console.log( p.getName() )
console.log( c.getName() )

缺点:父类构造函数被执行了两次,一次是在子类构造函数中,一次在赋值子类原型时,这是很多余的。

模式三、

var Parent = function(name){
    this.name = name || 'parent';
}

Parent.prototype = {
    obj:{a: 1},
    
    getName: function(){
        return this.name;
    }
}

var Child = function(name){
    Parent.apply(this, arguments); 
}

Child.prototype = Parent.prototype  //改进点

var p = new Parent();

var c = new Child('child');

console.log( p.getName() )
console.log( c.getName() )

缺点:子类的修改会改变父类的值。

模式四、

var Parent = function(name){
    this.name = name || 'parent';
}

Parent.prototype = {
    getName: function(){
        return this.name;
    },
    obj: {a:1}
}

var Child = function(){
    Parent.apply(this, arguments);
}

var F = function(){}

F.prototype = Parent.prototype;

Child.prototype = new F();

var p = new Parent('parent');
var c = new Child('child');

console.log(child.obj.a) ; //1
console.log(parent.obj.a) ; //1
child.obj.a = 2 ;
console.log(child.obj.a) ; //2
console.log(parent.obj.a) ; //2

模式五、

var deepClone = function(source,target){
    source = source || {} ;
    target = target || {};

    for(var i in source){
        if(source.hasOwnProperty(i)){

            if(typeof source[i] === 'object'){
                target[i] = (source[i] instanceof Array) ? [] : {};
                deepClone(source[i],target[i]) ;    
            }else{
                target[i] = source[i];
            }
        }
    }
    return target ;
} ;

var extend = function(Parent,Child){
    Child = Child || function(){} ;    
    if(Parent === undefined)        
        return Child ;    //借用父类构造函数
    Child = function(){
        Parent.apply(this,argument) ;
    } ;   
    //通过深拷贝继承父类原型    
    Child.prototype = deepClone(Parent.prototype) ;    
    //重置constructor属性
    Child.prototype.constructor = Child ;
} ;


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