ES6 类的继承

ES6中实现类的继承语法进行了优化,很类似于Java的语法,下面分别演示下ES5和ES6的两种语法。

  • ES 5 语法

prototype和__proto__不熟悉的同学,可以参照如下内容prototype和__proto__

	function Person(name, age) {
            this.name = name;
            this.age = age;
            this.innerFunction = function () {
                console.log("innerFunction")
            }
        }


        Person.prototype.show = function () {
            console.log(`${this.name},${this.age}`)
        }

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

        Student.prototype.__proto__=Person.prototype;
        var s1 = new Student('jack', 22, 'boy');
        var s2 = new Student('lucy', 21, 'girl');
        s1.show() //jack,22
        s2.show() //lucy,21
        console.log(s1.show===s2.show) //true
  • ES6 语法
	class Person {
            constructor(name, age) {
                this.name = name;
                this.age = age;
            }

            show() {
                console.log(this.name, this.age)
            }
        }

        class Student extends Person {
            constructor(name, age, sex) {
                super(name, age);
                this.sex = sex;

            }
        }

        let s1 = new Student('jack', 22, 'boy');
        let s2 = new Student('lucy', 21, 'girl');
        s1.show() //jack,22
        s2.show() //lucy,21
        console.log(s1.show === s2.show) //true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值