對javascript的理解
對象模型
紅色虛線表示隱式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指向系統(tǒng)內置的函數(shù)構造器(build-in Function constructor);Function具有自舉性;系統(tǒng)中所有函數(shù)都是由Function構造。
2. 左下角的obj1, obj2...objn范指用類似這樣的代碼創(chuàng)建的對象: function fn1(){}; var obj1=new fn1();這些對象沒有本地constructor方法,但它們將從Prototype鏈上得到一個繼承的constructor方法,即fn.prototype.constructor,從函數(shù)對象的構造過程可以知道,它就是fn本身了。
3.右下角的obj1, obj2...objn范指用類似這樣的代碼創(chuàng)建的對象: 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);這樣創(chuàng)建的對象,它的類型仍然是Number,即同樣需要根據(jù)參數(shù)值的類型來確定。同樣它們也沒有本地constructor,而是從Prototype鏈上獲得繼承的constructor方法,即build-in *** constructor,具體是哪一個由數(shù)據(jù)類型確定。
示例代碼
復制代碼 代碼如下:
//自定義對象代表,對應Javascript Object Model中的use defined functions
function Foo(){}
//自定義對象創(chuàng)建的對象實例的代表,對應Javascript Object Model中的objects that created by user defined functions
var foo = new Foo();
//String內置函數(shù)代表
//str為內置函數(shù)創(chuàng)建的對象實例的代表,對應Javascript Object Model中的objects that created by build-in constructors
var str = new String("string");
內存展現(xiàn)
你會發(fā)現(xiàn),它和《理解Javascript_09_Function與Object》中的內存分析圖是一樣的,為什么呢?在《數(shù)據(jù)模型》中提到過,內置對象都可以看作是函數(shù)的派生類型,例如Number instanceof Function為true,Number instanceof Object為true。在這個意義上,可以將它們跟用戶定義的函數(shù)等同看待。所以內置對象和自定義對象的創(chuàng)建流程是一樣的。
在理解了《Function與Object》的基礎上寫的,因此要理解本文必須理解Function與Object的關系!
【對javascript的理解】相關文章:
理解JavaScript原型鏈教程03-30
javascript的閉包概念怎么理解03-29
淺談javascript中的單線程理解03-30
有關深入理解JavaScript中的并行處理的介紹03-30
JavaScript的課堂講解03-31
JavaScript 基礎教學04-01
JavaScript學習筆記03-30
常用的JavaScript模式03-10