之所以說換個角度是指我現(xiàn)在對javascript的理解與我以往對javascript的理解。在這種理解的轉變中最大的轉變是對函數(shù)的理解,以及隨之而來的對javascript的對象,尤其是對象屬性的理解上的變化。簡單的說,現(xiàn)在理解的函數(shù),不是和變量類型同級的概念,而是變量類型的一種,即函數(shù)也是一個對象,一個可以象數(shù)字,字符串一樣賦值給一個變量的實體。這個和C里將指針指向函數(shù)有些類似,但我一直都是把javascript類比java來理解。
首先對javascript的類型再熟悉一遍javascript中變量(variable)的值(value)有這樣幾種類型(type):
(ECMAscript Language Specification Edition 3 24-Mar-00)
8.1 The Undefined TypeThe
Undefined type has exactly one value, called undefined. Any variable
that has not been assigned a value has the value undefined.
8.2 The Null TypeThe Null type has exactly one value, called null.
8.3 The Boolean TypeThe Boolean type represents a logical entity having two values, called true and false.
8.4 The String TypeThe String type is the set of all finite ordered sequences of zero or more 16-bit unsigned integer values
(“elements”).
8.5 The Number TypeThe Number type has exactly 18437736874454810627 (that is, 264?253+3) values, representing the doubleprecision
64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic,
except that the 9007199254740990 (that is, 253?2) distinct “Not-a-Number” values of the IEEE Standard are
represented in ECMAscript as a single special NaN value. (Note that the NaN value is produced by the program
expression NaN, assuming that the globally defined variable NaN has not been altered by program execution.)
8.6 The Object TypeAn Object is an unordered collection of properties. Each property consists of a name, a value and a set of attributes.
我們比較關注面向對象,所以對其中的Object類型多加留意。
如上面的定義,Object類型是無序的屬性的集合。每個屬性(property)有名稱,值和一些性質(attributes)(如只讀,可枚舉,不可刪,內(nèi)部的)。
舉幾個例子:
var a;//a現(xiàn)在對應一個值,該值的類型是
Undefined
a = 1;//現(xiàn)在a對應一個Number類型的值
a = true;//現(xiàn)在a的類型變了,變成一個Boolean類型的值。
a = "x";//a現(xiàn)在對應一個String類型的值
//(注意"x"和new String("x")并不相同)
//說到這里想到javascript里兩個相等操作符==和===
//==只針對基本的數(shù)據(jù)類型,不對Object,如果待比較的兩個值都是Object的話
//返回false,除非是同一個對象,如果有有一個是Object的話,將之轉化為和另外一個值相同類型的值
//然后進行比較。===則要求兩者類型也相同。
var b = new String("x");
alert(a == b);//true
alert(a===b);//false 因為類型不同
alert(typeof a);//string
alert(typeof b);//object
a = {};
//查看類型的方法是typeof,可以寫成typeof a也可以寫成typeof(a)
//參看typeof的說明
alert(typeof a);//object
alert(typeof true);//boolean
alert(typeof(typeof true))//string
typeof的執(zhí)行邏輯Undefined | "undefined" |
Null
| "object" |
Boolean | "boolean" |
Number | "number" |
String | "string" |
Object (native and doesn’t implement [[Call]]) | "object" |
Object (native and implements [[Call]]) | "function" |
Object (host)
| Implementation-dependent
|
從上面可以看到對于Object類型,typeof根據(jù)值的情況返回object或function。
(注:所謂implement [[Call]]我的理解就是指是否可以作為函數(shù)調(diào)用
,native有兩種一種是內(nèi)置的如Array,Date等另一種是用戶自己定義的。除此之外就是host即javascript的宿主提供的一些對象。)