继承2T

2019-07-09  本文已影响0人  关耳木南
<script type="text/javascript">
    /*
        继承:
            儿子继承老子
        私有属性
        共有属性

     */
    //父类
    function P1(opt){
        // this.name = opt.name;
        // this.age = opt.age
    }
    P1.prototype.sayName = function(){
        alert(this.name)
    }

    //子类  需要继承父类P1
    function P2(opt){
        //继承 私有
        P1.call(this,opt);
        //自行扩展
        this.sex = opt.sex;
    }
// 
    P2.prototype = new P1();
    P2.prototype.sayAge = function(){
        console.log(this.name)
    };
    const o1 = new P1({
        name:"胡歌1",
        age:"20",
        sex:"男"
    })
    const o2 = new P2({
        name:"胡歌",
        age:"23",
        sex:"男"
    })
    o1.sayName();
</script>
上一篇 下一篇

猜你喜欢

热点阅读