继承2T

作者: 关耳木南 | 来源:发表于2019-07-09 16:24 被阅读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>

相关文章

网友评论

      本文标题:继承2T

      本文链接:https://www.haomeiwen.com/subject/gexfkctx.html