Js 原型鏈

Js 原型鏈
  • 原型鏈查找機制函數

    每當代碼讀取某個對象的某個屬性時,都會執行一次搜索,目標時具備給定名字的屬性:this

    ①搜索首先從對象實例自己開始prototype

    ②若是在實例中找到了具備給定名字的屬性,則返回該屬性的值指針

    ③若是沒有找到,則繼續搜索指針指向的原型對象,在原型對象中查找具備給定名字的屬性code

    ④若是在原型對象中找到了這個屬性,則返回該屬性的值對象

function Student(name,id){
    this.name = name;
    this.id = id;
   }
   
   //獲取對象的prototype
    Student.prototype.type = "student";
    Student.prototype.message = function(){
        console.log(this.name + "," + this.id);
    };
   ​
   var student1 = new Student("li",111);
   var o = student1.__proto__; //指向的是Student構造函數的原型對象
   var o1 = o.__proto__;//指向的是o的原型對象,也就是Student原型對象的原型對象
   ​
   console.log(o1.constructor);//結果顯示Object(){}
   console.log(o1);//Object
   console.log(o1.__proto__);//null </pre>
  • 實例對象讀寫原型對象成員blog

    • 先在本身身上找,找到即返回,若是找不到則沿着原型鏈向上查找,若是一直到原型鏈末端還未找到,則返回undefined原型鏈

    • ①值類型成員寫入(實例對象.值類型成員 = xx)
            經過實例重寫原型對象中某個普通數據成員時,會把該成員添加到本身身上,屏蔽掉對原型對象成員的訪問;
      ②引用類型成員寫入(實例對象.引用類型成員 = xx)
            經過實例對象添加新成員,會直接添加給本身,屏蔽掉對原型對象的訪問。原型

這兩種寫入都屏蔽掉對原型對象的訪問,直接添加到本身身上。io

function Student(name,id){
             this.name = name;
             this.id = id;
             }
            ​
             //獲取對象的prototype
             Student.prototype.type = "student";
             Student.prototype.message = function(){
             console.log(this.name + "," + this.id);
             };
             //生成實例對象
             var student1 = new Student("li",111);
            ​
             student1.sex = "male";//給student1添加sex屬性
             student1.type = "teacher";//重寫type
             console.dir(student1);</pre>

image.png

  • 複雜類型成員修改(實例對象.成員.xx = xx)
       與值類型和引用類型的寫入不同,複雜類型成員先在自身找該成員,找到直接修改,若是找不到,則沿着原型鏈繼續查找,如果一直到原型鏈末端還未找到,則報錯。仍是會進行原型鏈的查找。
// 添加一個新的屬性給原型對象,值是一個對象類型
             Student.prototype.score = {
             mathScore:90
             };
            ​
             //經過實例對象修改對象中複雜類型數據中的內容
             student1.score.mathScore = 98;
             console.dir(student1);

image.png

相關文章
相關標籤/搜索