js __proto__和prototype的關係

前言

           小夥伴們,在js的學習道路上你們,必定會碰到實例上的__proto__和構造函數上的prototype,這兩個屬性,你們對這兩個屬性的關係,理解完全嗎?我反正以前是不太清楚。今天我看了一些高程三上的知識,分享給你們。

js中函數的身份

  • 普通的函數
  • js對象
  • 構造函數

           其實js中的函數,很像我們人類,在不一樣的環境,扮演者不一樣的身份。好比我bash

  • 在公司是一名員工
  • 在社會上是一名公民
  • 在父母眼中是一個孩子

           小夥伴看一下,這種角色扮演,沒有毛病吧,我們這麼一結合和,發現js 是否是頗有趣。函數

     當函數扮演普通函數的時候,他就是一個函數,用來完成每一個功能或者過個功能的方法。      當函數扮演普通js對象的時候,他就是一個對象,有本身私有屬性、方法和繼承父級的的屬性、方法學習

     當函數扮演構造函數的時候,他就是一個構造函數,使用new就能夠建立出實例。this

           不管何時,只要建立了一個新函數,就會根據一組特定的規則爲該函數建立一個 prototype 屬性,這個屬性指向函數的原型對象,在默認狀況下,全部原型對象都會自動得到一個 constructor (構造函數)屬性, 這個屬性是一個指向 prototype 屬性所在函數的指針。 就拿前面的例子來講, Person.prototype.constructor 指向 Person。而經過這個構造函數,咱們還可繼續爲原型對象添 加其餘屬性和方法。咱們能夠的到一個恆等的公式 Person.prototype.constructor===Personspa

也能夠在prototype的屬性上添加一些實例共享的方法、屬性prototype

function Person(){ }

Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){ alert(this.name); };
var person1 = new Person(); 
person1.sayName(); //"Nicholas"
複製代碼

           每一個實例都會有個__proto__屬性,這個屬性是一個引用地址,指向該構造函數的prototype的指針上。

       那麼我們就會獲得一個恆等的公式

原型鏈

           看代碼
function Person(){ }

Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){ alert(this.name); };
var person1 = new Person();
person1.sayName(); //"Nicholas"
person1.age; // 29
複製代碼

上面的例子我們看到了實例person1的age是29 ,那麼age是怎麼找到的呢,首先會去person1的私有屬性(自己的屬性),有沒有age,若是有的話就去這個屬性的值,若是沒有就會查找person1.__proto__指向上的對象(Person.prototype)有沒有該屬性有的話就會返回該屬性的值,若是沒有接着查找person1.proto.__proto__直到Object.prototype指向的對象有沒有,沒有的就返回undefined。上述的查找過程就是做用域鏈。指針

           構造函數的原型屬性是不能夠經過實例的進行來修改的,看代碼code

function Person(){ }

Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){ alert(this.name); };
var person1 = new Person();
var person2 = new Person();
person1.age = 39;
console.log(person1.age)//39
console.log(person2.age)// 29
複製代碼

           直接給實例屬性添加value的話和添加到實例的私有屬性上。怎麼判斷數屬性是私有仍是構造函數的原型上面的呢,看代碼cdn

function Person(){ }

Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){ alert(this.name); };
var person1 = new Person();
var person2 = new Person();
person1.age = 39;
person1.hasOwnProperty('age')//true
person2.hasOwnProperty('age')//false

複製代碼

           怎麼判斷實例是否屬於該構造函數使用 Object.getPrototypeOf(new Person),返回的是Person.prototype對象

function Person(){ }

Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){ alert(this.name); };
var person1 = new Person();
var person2 = new Person();
Object.getPrototypeOf(person1)===Person.prototype//true
Object.getPrototypeOf(person2)===Person.prototype// true

複製代碼
相關文章
相關標籤/搜索