JavaScript对象之面向对象的三种继承方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>INHERTIED</title>


    <script charset="utf-8" type="text/javascript">

        /*
         * 原型继承的特点:
         * 即继承了父类的模版 又继承了父类的原型对象
         */
        function Person(name,age) {
            this.name = name;
            this.age = age;
        }


        //父类的原型对象属性
        Person.prototype.id = 10;


        function Son(sex) {
            this.sex = sex;
        }


        Son.prototype = new Person('Tom',22);
        var s = new Son('M');

        document.write(s.name + ', ' + s.age + ', ' + s.sex + ', ' + s.id + '<br>');



        /*
         *类继承
         *只继承类模版,不继承原型对象(借用构造函数的方式继承)
         */
        function Father(name,age) {
            this.name = name;
            this.age = age;
        }

        Father.prototype.id = 'No1234';

        function Boy(name,age,sex) {
            Person.call(this,name,age);
            this.sex = sex;
        }


        var b = new Boy('z3',23,'W');
        document.write(b.name + ', ' + b.age + ', ' + b.sex + ', ' + b.id + '<br>');


        
        /*
         *混合继承 = 原型对象 + 借用构造函数继承
         */
        function BasedClass(name,age) {
            this.name = name;
            this.age = age;
        }

        //父类的原型对象属性
        BasedClass.prototype.id = 'No12345';
        BasedClass.prototype.sayHi = function () {
            document.write('Hi' + '<br>');
        }
        
        
        function InheritedClass(name,age,sex) {
            BasedClass.call(this,name,age); //借用构造函数继承
            this.sex = sex;
        }

        //原型继承
        //只剩下 父类的实例 和 父类的原型对象的关系
        InheritedClass.prototype = new BasedClass();  //继承父类的原型对象

        var inh = new InheritedClass('w5',25,'W');
        document.write(inh.name + ', ' + inh.age + ', ' + inh.sex + ', ' + inh.id + '<br>');
        inh.sayHi();
        
        

    </script>

</head>
<body>

</body>
</html>


结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值