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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章