js分家效应

(原创文章,转载请注明出处)

有继承,那么就有分家。让我们看以下例子。

    var parents = function(){
    }
    parents.prototype.money = 200;

    var children = function(){

    }
    children.prototype = new parents();
    

    var parent = new parents();
    var child = new children();
    //分家前,父亲的就是儿子的
    parents.prototype.money = 300;
    console.log(parent.money + "," + child.money); //300,300//儿子赚钱了,父亲的是父亲的,儿子是儿子的
    children.prototype.money = 400;
    console.log(parent.money + "," + child.money);//300,400
    //从此分家,各过各的
    parents.prototype.money = 300;
    console.log(parent.money + "," + child.money); //300,400

    children.prototype.money = 400;
    console.log(parent.money + "," + child.money);//300,400

子类继承后,子类不重写父类的方法,则子类和父类公用一个方法。父类重写方法,也会自动由子类继承。

子类重写父类的方法后,父类和子类不再共用方法。---分家

原文地址:https://www.cnblogs.com/linchaoqun/p/4745809.html