天天看點

JavaScript——面向對象程式設計之繼承

文章目錄

    • 原型繼承(Es6之前)
    • class繼承(Es6新特性)
    • 原型鍊

原型繼承(Es6之前)

原型對象(類)

對象:具體執行個體

var student = {
  name : "shenming",
  age : 3,
  sex : '男',
  run:function(){
     console.log(this.name +"快跑");
  }
};


var xiaomimg = {
  name : "taoxian"
};

//原型繼承 把xiaomimg的原型指向了student(原型對象),繼承後xiaoming也可以調研student方法
xiaomimg.__proto__=student;

xiaomimg.run()
 taoxian快跑
student.run()
 shenming快跑
           

class繼承(Es6新特性)

定義一個類(包含屬性,方法)

//定義一個學生類
        class student{
           constructor(name){//構造函數
             this.name = "shenming"
           }
          hello(){
            alert("桃仙")
          }
        }

//定義學生類的變量(可以多個)
 var xiaoming = new student("xiaoming");
 var taoxian = new student("taoxian");
//類的使用
xiaoming.hello()
xiaoming.name
taoxian.hello()
taoxian.name
           

class繼承

//定義一個學生類
        class Student{
           constructor(name){
             this.name = "shenming"
           }
          hello(){
            alert('hello')
          }
        }
        //class繼承
        class XiaoStudent extends Student{
          constructor(name,grade){
             super(name);
             this.grade = grade;
          }
          myGrade(){
            alert('國小生')
          }
        }

        //定義學生類的變量,繼承後,通過變量調用XiaoStudent 裡的方法
        var xiaoming = new Student("xiaoming");
        var taoxian = new Student("taoxian");
           

class繼承的本質還是指向原型(類),隻不過寫法更容易接受

原型鍊

prototype屬性

在JavaScript中,每個函數都有一個prototype屬性,這個屬性指向函數的原型對象。

__ proto __屬性

這是每個對象(除null外)都會有的屬性,叫做proto,這個屬性會指向該對象的原型。

每個對象都可以有一個原型_proto_,這個原型還可以有它自己的原型,以此類推,形成一個原型鍊。查找特定屬性的時候,我們先去這個對象裡去找,如果沒有的話就去它的原型對象裡面去,如果還是沒有的話再去向原型對象的原型對象裡去尋找… 這個操作被委托在整個原型鍊上,這個就是我們說的原型鍊了。

連結:https://www.jianshu.com/p/08c07a953fa0

繼續閱讀