完美实现javascript继承

js的继承 主要是继承两个部分

一个是写在函数体内 通过 this 定义的方法和属性


代码

function parent(){
    this.name = 1;
    this.fuck = function(){
        
    }
}

继承这种方法需要在初始化的时候进行继承,我看许多其他的例子 是通过实例化之后 进行处理,我觉得这样写 就没有继承的样子了,而且子类无法进行属性和方法重写

所以我换了个方式


首先定义一个方法

function getParent(instance,parent,arg){
        instance.extend = parent;
        instance.extend.apply(instance,arg);//传递参数
        instance.extend = null;
        delete instance.extend;
    }

然后每次定义一个新的类,只需要在function体内的第一行,调用这个方法即可

完整的代码如下

function getParent(instance,parent,arg){
    instance.extend = parent;
    instance.extend.apply(instance,arg);//传递参数
    instance.extend = null;
    delete instance.extend;
}


function Parent(){
    this.name = '老王';
    this.daren = function(){
        console.log('我是'+this.name+',我要打人了');
    }
}

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

var laoWang = new Parent();
laoWang.daren();

var xiaoMing = new Child('小明');
xiaoMing.daren();

var xiaoMing = new Child('小明的妹妹');
xiaoMing.daren();


运行结果





好上述的方法继承完毕,咱们还需要继承prototype中的方法,这个好办,咱们直接给Function写个扩展


Function.prototype.extend = function(parent){
    this.prototype = parent.prototype;
};



好完整的代码如下

function getParent(instance,parent,arg){
    instance.extend = parent;
    instance.extend.apply(instance,arg);//传递参数
    instance.extend = null;
    delete instance.extend;
}

Function.prototype.extend = function(parent){
    this.prototype = parent.prototype;
};

function Parent(){
    this.name = '老王';
    this.daren = function(){
        console.log('我是'+this.name+',我要打人了');
    }
}
Parent.prototype = {
    chuanmen:function(){
        console.log('我是'+this.name+',我去串门了');
    }
};

function Child(name){
    getParent(this,Parent,arguments);
    this.name = name;
}
Child.extend(Parent);

var laoWang = new Parent();
laoWang.daren();
laoWang.chuanmen();

var xiaoMing = new Child('小明');
xiaoMing.daren();
laoWang.chuanmen();

var xiaoMing = new Child('小明的妹妹');
xiaoMing.daren();
laoWang.chuanmen();

大家去试试看吧

猜你喜欢

转载自blog.csdn.net/qiushi888/article/details/51133470