Javascript继承

class 定义类型

class 声明类型要点

  • JS中extends实现继承
  • super 调用父类,super调用父类构造函数时,必须写在this之前
  • 在ES6中类没有变量提升,所以必须先定义类,才能通过类实例化对象
  • 类里面的共有属性和方法必须加this

this 指向的问题也很重要,是js中一直存在的问题

instance

class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            };
            sum() {
                console.log(this.x + this.y);
            };

            say() {
                console.log('this is father');
            }
        }

        class Son extends Father {
            constructor(x, y, z) {
                super(x, y);//super 必须写在this 之前
                this.z = z;
            };

            say() {
                super.say();
                console.log('this is son');
            }

            sub() {
                console.log(this.x - this.y);
            }

        }

        var son1 = new Son(1, 2, 4);
        son1.sum();
        son1.say();
        son1.sub();

属性继承

<script>
        function Father(uname, age) {
            this.uname = uname;
            this.age = age;
        }


        function Son(uname, age, gender) {
            Father.call(this, uname, age);
            this.gender = gender;
        }
        var son = new Son('test', 20, 'male');
        console.log(son);
    </script>

方法继承

<script>
        function Father(uname, age) {
            this.uname = uname;
            this.age = age;
        }

        Father.prototype.run = function () {
            console.log('father run');
        }


        function Son(uname, age, gender) {
            Father.call(this, uname, age);
            this.gender = gender;
        }
        //方法继承
        Son.prototype = new Father();
        //重置constructor
        Son.prototype.constructor = Son;
        var son = new Son('test', 20, 'male');
        console.log(son);

    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值