Js各种继承方法总结

来源:互联网 发布:mysql 创建触发器 编辑:程序博客网 时间:2024/04/30 22:29
//原型链方式    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对象的方法



0 0
原创粉丝点击