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>

你可能感兴趣的:(javascript,js,class)