[Javascript] Javascript實作繼承的方式,ES5兩行程式碼記住!

test

在恆逸的上課筆記,因為老是忘記Javascript如何實作繼承,乾脆寫在部落格

ES5語法↓

        // Base constructor.
        var Person = function (name, age) {
            this.name = name;
            this.age = age;
        };

        // Base prototype.
        Person.prototype = {
            haveBirthday: function () {
                this.age++;
            }
        };

        // Derived constructor.
        var Student = function (name, age, subject) {
            this.name = name;
            this.age = age;
            this.subject = subject;
        };

        // Set the derived prototype to be the same object as the base prototype,
        // and reset that derived prototype so that it uses the correct constructor.
          Student.prototype = new Person();//將Student的prototype基底類別指向Person物件
          Student.prototype.constructor = Student;//上一行程式碼讓Student.prototype.constructor消失,此行將Student.prototype.constructor修正回正確的constructor
        


      // Create a derived object and invoke any methods defined in the object or one of its // parents. JavaScript uses prototype chaining to locate methods up the inheritance tree.
      // var aStudent = new Student("Jim", 20, "Physics");
     //  aStudent.subject = "BioChemistry";
     //   aStudent.haveBirthday();
     //  alert(aStudent.age);

ES6語法↓


         
        class Person{
            constructor(name, age){
                this.name=name;
                this.age=age;
            }
            haveBirthday(){
                this.age++;
            }
        }

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


       
       /* var aStudent = new Student("Jim", 20, "Physics");
        aStudent.subject = "BioChemistry";
        aStudent.haveBirthday();
        alert(aStudent.age);
        */