之所以说换个角度是指我现在对javascript的理解与我以往对javascript的理解。在这种理解的转变中最大的转变是对函数的理解,以及随之而来的对javascript的对象,尤其是对象属性的理解上的变化。简单的说,现在理解的函数,不是和变量类型同级的概念,而是变量类型的一种,即函数也是一个对象,一个可以象数字,字符串一样赋值给一个变量的实体。这个和C里将指针指向函数有些类似,但我一直都是把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)(如只读,可枚举,不可删,内部的)。
举几个例子:
var a;//a现在对应一个值,该值的类型是
Undefined
a = 1;//现在a对应一个Number类型的值
a = true;//现在a的类型变了,变成一个Boolean类型的值。
a = "x";//a现在对应一个String类型的值
//(注意"x"和new String("x")并不相同)
//说到这里想到javascript里两个相等操作符==和===
//==只针对基本的数据类型,不对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的执行逻辑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根据值的情况返回object或function。
(注:所谓implement [[Call]]我的理解就是指是否可以作为函数调用
,native有两种一种是内置的如Array,Date等另一种是用户自己定义的。除此之外就是host即javascript的宿主提供的一些对象。)