欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript原型和原型鏈與構(gòu)造函數(shù)和實例之間的關(guān)系詳解

 更新時間:2022年07月21日 10:25:01   作者:大蓮芒  
這篇文章主要介紹了JavaScript原型和原型鏈與構(gòu)造函數(shù)和實例之間的關(guān)系,每個對象都連接到一個原型對象,并且它可以從中繼承屬性。所有通過對象字面量創(chuàng)建的對象都連接到object.prototype,它是JavaScript中的標配對象

原型

如圖所示:

1.instanceof檢測構(gòu)造函數(shù)與實例的關(guān)系:

function Person () {.........}

person = new Person ()

res = person instanceof Person

res  // true

2.實例繼承原型上的定義的屬性:

function Person () {........}

Person.prototype.type = 'object n'

person = new Person ()

res = person.type

res  // object n

3.實例訪問 ===> 原型

實例通過__proto__訪問到原型 person.proto=== Person.prototype

4.原型訪問 ===> 構(gòu)造函數(shù)

原型通過constructor屬性訪問構(gòu)造函數(shù) Person.prototype.constructor === Person

5.實例訪問===>構(gòu)造函數(shù)

person.proto.constructor === Person

原型鏈

在讀取一個實例的屬性的過程中,如果屬性在該實例中沒有找到,那么就會循著 proto 指定的原型上去尋找,如果還找不到,則尋找原型的原型:

1.實例上尋找

function Person() {}

    Person.prototype.type = "object name Person";
    person = new Person();
    person.type = "我是實例的自有屬性";
    res = Reflect.ownKeys(person); //嘗試獲取到自有屬性
    console.log(res);
    res = person.type;
    console.log(res); //我是實例的自有屬性(通過原型鏈向上搜索優(yōu)先搜索實例里的)

2.原型上尋找

function Person() {}

    Person.prototype.type = "object name Person";
    person = new Person();
    res = Reflect.ownKeys(person); //嘗試獲取到自有屬性
    console.log(res);
    res = person.type;
    console.log(res); //object name Person

3.原型的原型上尋找

function Person() {}

    Person.prototype.type = "object name Person";
    function Child() {}
    Child.prototype = new Person();
    p = new Child();
    res = [p instanceof Object, p instanceof Person, p instanceof Child];
    console.log(res); //[true, true, true] p同時屬于Object,Person, Child
    res = p.type; //層層搜索
    console.log(res); //object name Person (原型鏈上搜索)
    console.dir(Person);
    console.dir(Child);

4.原型鏈上搜索

  • 原型同樣也可以通過 proto 訪問到原型的原型,比方說這里有個構(gòu)造函數(shù) Child 然后“繼承”前者的有一個構(gòu)造函數(shù) Person,然后 new Child 得到實例 p;
  • 當訪問 p 中的一個非自有屬性的時候,就會通過 proto 作為橋梁連接起來的一系列原型、原型的原型、原型的原型的原型直到 Object 構(gòu)造函數(shù)為止;
  • 原型鏈搜索搜到 null 為止,搜不到那訪問的這個屬性就停止:

function Person() {}

  Person.prototype.type = "object name Person";
  function Child() {}
  Child.prototype = new Person();
  p = new Child();
  res = p.__proto__;
  console.log(res);         //Person {}
  res = p.__proto__.__proto__;
  console.log(res);         //Person {type:'object name Person'}
  res = p.__proto__.__proto__.__proto__;
  console.log(res);         //{.....}
  res = p.__proto__.__proto__.__proto__.__proto__;
  console.log(res);         //null

到此這篇關(guān)于JavaScript原型和原型鏈與構(gòu)造函數(shù)和實例之間的關(guān)系詳解的文章就介紹到這了,更多相關(guān)JavaScript原型與原型鏈內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論