理解Javascript_10_物件模型_javascript技巧

來源:互聯網
上載者:User
物件模型

紅色虛線表示隱式Prototype鏈。
這張物件模型圖表中包含了太多東西,不少地方需要仔細體會,可以寫些測試代碼進行驗證。徹底理解了這張圖,對JavaScript語言的瞭解也就差不多了。下面是一些補充說明:
1. 圖中有好幾個地方提到build-in Function constructor,這是同一個對象,可以測實驗證:
複製代碼 代碼如下:

//Passed in FF2.0, IE7, Opera9.25, Safari3.0.4
Function==Function.constructor //result: true
Function==Function.prototype.constructor //result: true
Function==Object.constructor //result: true
//Function also equals to Number.constructor, String.constructor, Array.constructor, RegExp.constructor, etc.
function fn(){}
Function==fn.constructor //result: true

這說明了幾個問題: Function指向系統內建的函數構造器(build-in Function constructor);Function具有自舉性;系統中所有函數都是由Function構造。

2. 左下角的obj1, obj2...objn範指用類似這樣的代碼建立的對象: function fn1(){}; var obj1=new fn1();這些對象沒有本地constructor方法,但它們將從Prototype鏈上得到一個繼承的constructor方法,即fn.prototype.constructor,從函數對象的構造過程可以知道,它就是fn本身了。


3.右下角的obj1, obj2...objn範指用類似這樣的代碼建立的對象: var obj1=new Object();或var obj1={};或var obj1=new Number(123);或obj1=/\w+/;等等。所以這些對象Prototype鏈的指向、從Prototype鏈繼承而來的 constructor的值(指它們的constructor是build-in Number constructor還是build-in Object constructor等)等依賴於具體的物件類型。另外注意的是,var obj=new Object(123);這樣建立的對象,它的類型仍然是Number,即同樣需要根據參數值的類型來確定。同樣它們也沒有本地constructor,而是從Prototype鏈上獲得繼承的constructor方法,即build-in *** constructor,具體是哪一個由資料類型確定。
範例程式碼

複製代碼 代碼如下:

//自訂對象代表,對應Javascript Object Model中的use defined functions
function Foo(){}
//自訂對象建立的對象執行個體的代表,對應Javascript Object Model中的objects that created by user defined functions
var foo = new Foo();
//String內建函數代表
//str為內建函數建立的對象執行個體的代表,對應Javascript Object Model中的objects that created by build-in constructors
var str = new String("string");


記憶體展現

你會發現,它和《理解Javascript_09_Function與Object》中的記憶體分析圖是一樣的,為什麼呢?在《資料模型》中提到過,內建對象都可以看作是函數的衍生類別型,例如Number instanceof Function為true,Number instanceof Object為true。在這個意義上,可以將它們跟使用者定義的函數等同看待。所以內建對象和自訂對象的建立流程是一樣的。

在篇博文是在理解了《Function與Object》的基礎上寫的,因此要理解本文必須理解Function與Object的關係!

最後寫一點感言:令人發狂的理論!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.