继承的多种方式

常用的继承方法:
1.原生继承

/ 抽取共同点
        /* 人类 */
        function People(name, age, sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        People.prototype.say = function() {
            console.log("hahahahha");
        }
        People.prototype.breath = function() {
            console.log("hu~~~~~xi~~~~~");
        }
        /* 学生类 */
        function Student (name, age, sex, studentNO) {
            // this 是Student的实例
            // 构造函数式继承 也叫做类式继承
            People.call(this, name, age, sex); // People被执行 并 this改为Student的实例 等价于以下三条 之所以这么写是为了复用代码
            // this.name = name;
            // this.age = age;
            // this.sex = sex;
            this.studentNO = studentNO;
        }
        // Student既然继承了People除了要有People的属性之外 还要有People的方法
        // 将Student的原型指向People的实例 叫做原型式继承
        Student.prototype = new People();
        // 因为丢了原来的原型 所以constructor属性也就丢失了需要补回 
        // 补回操作与增加新方法的操作 一定要在继承完毕之后再执行
        Student.prototype.constructor = Student;
        Student.prototype.study = function() {
            console.log("学习");
        }
        /* 老师类 */
        function Teacher(name, age, sex, jiaobian) {
            People.call(this, name, age, sex);
            this.jiaobian = jiaobian;
        }
        Teacher.prototype = new People();
        // delete Teacher.prototype.name;
        // delete Teacher.prototype.age;
        // delete Teacher.prototype.sex;
        Teacher.prototype.constructor = Teacher;
        Teacher.prototype.teach = function() {
            console.log("教书");
        }
					2.寄生式
// 想要让学生类的实例拥有People类的方法 
        // var F = function() {

        // }
        // F.prototype = People.prototype;
        // var f = new F();
			3.构造式:构造函数式继承 它是专门用于继承属性的
People.call(this, name, age, sex);
			4.Es6中的继承
 <script>
        // ES6中的定义类
        class People {
            // 类中的构造函数
            constructor(name, age, sex) {
                // 属性定义在这里
                this.name = name;
                this.age = age;
                this.sex = sex;
            }
            // 方法定义在这里
            breath() {
                console.log("呼~~~~吸~~~~");
            }
        }
        // ES6中的继承
        class Student extends People {
            constructor(name, age, sex, studentNO) {
                // 必须调用super
                super(name, age, sex);
                this.studentNO = studentNO;
                console.log("hahahaha")
            }
        }
        // 初始化实例
        var s = new Student("小白", 15, "男", 123);
        
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值