JavaScript 原型理解

來源:互聯網
上載者:User

標籤:UNC   strong   臨時   tor   臨時對象   代碼   factory   解決   rip   

 建立一個對象可以通過對象字面量的方式:
var stu = {    name:"張三",    sayname:function(){        console.log(this.name);    }

 

可是,我們要建立多個stu對象總不能把上面代碼重複寫很多次吧?

我們可以使用最簡單的工廠函數,返回一個對象:

 

function stuFactory (name){    return {        name:name,        sayname:function(){            console.log(this.name);        }    }}//這樣產生執行個體對象var stu1 = stuFactory("趙四");var stu2 = stuFactory("王五");

 

但是這樣有一個問題,即誰建立了這兩個對象?

更優雅的方式:建構函式

所謂建構函式,需通過 new Constructor() 的方式建立對象。


 function stuMaker(){            this.name = name,            this.sayname = function(){                console.log(this.name);            }        } var stu3 = new stuMaker("尼古拉斯"); var stu4 = new stuMaker("尼古拉斯-趙四");

 

這個 new 關鍵字發生了什嗎?

function stuMaker(){            //建立一個臨時對象            var instacne = {},            //執行個體綁定到this            this = instacne,            this.name = name,            this.sayname = function(){                console.log(this.name);            }            //返回this            return this;        }

 

總結就是:

  1. 建立一個臨時對象儲存執行個體

  2. 將 this 指向該臨時對象

  3. 返回這個對象

但是,這樣還不是很優雅,假如這個學生對象有共有屬性,每次建立一個執行個體對象,就會把這個共有屬性建立一次,不合理,JavaScript 為瞭解決這個問題,規定了每個函數都有一個 Prototype 屬性,這個屬性可以幹嘛呢?

這個屬性可以指向一個 constructor 的對象,這個對象有個屬性 constructor 指向該建構函式


  function 建構函式(){           prototype:constructor //簡單寫就是這樣一個對象:constructor{constructor::建構函式}        }

 

我們通過該建構函式建立的執行個體對象有個__proto__屬性指向一個對象,這個對象就是上面:

建構函式prototype 所指的對象

簡言之:

建構函式.prototype === 執行個體對象.__proto__;

這麼做有什麼意義呢?

建構函式的 prototype 把共有屬性預定好,然後再建立對象的時候,順手讓執行個體對象的proto屬性指向這個對象,好處就是執行個體對象可以通過proto知道自己共有屬性有哪些。

總感覺還是沒能徹底理解js 的原型 ,解釋起來非常費勁,暫且就這樣吧,有了更加通俗易懂的方式,再來填坑。

JavaScript 原型理解

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.