Js各种继承方法总结

//原型链方式
    function ClassA() {

    }
    ClassA.prototype.color = "red";
    ClassA.prototype.sayColor = function () {
        console.log(this.color);
    }

    function ClassB() {}
    ClassB.prototype = new ClassA();
    var b = new ClassB();
    console.log(b.sayColor());
   
    //call方法继承
    function ClassA(sColor, sName) {
        this.sColor = sColor;
        this.sName = sName;
        this.sayColor = function () {
            console.log(this.sColor);
        }
    }

    function ClassB(sColor, sName, type) {
        ClassA.call(this, sColor, sName);
        this.type = type;
        this.show = function () {
            console.log(this.sColor + " " + this.sName + " " + this.type);
        }
    }
    var b = new ClassB("red", "color_1", "color");
    console.log(b.sayColor());
    console.log(b.show());
call方法,即调用一个对象的一个方法,以另一个对象替换当前对象。

在我打的这个例子中,可以看做ClassA对象代替this对象在ClassB中执行,那么就实现了ClassB对ClassA的继承。

    //apply方法继承
    function ClassA(sColor, sName) {
        this.sColor = sColor;
        this.sName = sName;
        this.sayColor = function () {
            console.log(this.sColor);
        }
    }

    function ClassC(sColor, sName, type) {
        this.type = type;
        ClassA.apply(this, arguments);
        this.show = function () {
            console.log(this.sColor + " " + this.sName + " " + this.type);
        }
    }
    var c = new ClassC("blue", "color_2", "color");
    console.log(c.sayColor());
    console.log(b.show());
apply方法的作用与call方法类似,只是第二个参数不一样,传入的第二个参数是一个数组。

    //对象冒充
    function ClassA(sColor) {
        this.sColor = sColor;
        this.sayColor = function () {
            console.log(this.sColor);
        }
    }

    function ClassB(sColor, sName) { //把ClassB看作构造函数
        this.method = ClassA; //定义成员方法,把函数ClassA作为成员方法
        this.method(sColor); //执行成员方法,相当于new一个ClassA
        delete this.method;
        this.sName = sName;
        this.show = function () {
            console.log(this.sColor + " " + this.sName);
        }
    }
    var b = new ClassB("white", "color_3");
    console.log(b.sayColor());
    console.log(b.show());
事实上call和apply也是像这种一样的对象冒充继承方法
    //混合方式
    function ClassA(sColor) {
        this.sColor = sColor;
    }
    ClassA.prototype.sayColor = function () {
        console.log(this.sColor);
    }

    function ClassB(sColor, name) {
        ClassA.call(this, sColor);
        this.name = name;
    }
    ClassB.prototype = new ClassA();
    ClassB.prototype.show=function(){
        console.log(this.sColor+" "+this.name);
    }
    var b = new ClassB("black", "color_4");
    console.log(b.sayColor());
    console.log(b.show());
利用call和原型链的混合方式,应该是比较合理的方式了,对象的属性要么来自自身属性,要么来自prototype,
在混合方式中,用call方式继承父类函数的属性,用原型链方式继承父类prototype对象的方法



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值