/**JavaScript 对象是词典*/
var userObject = {}; // equivalent to new Object()
userObject.lastLoginTime = new Date();
alert(userObject["lastLoginTime"]);
/**JavaScript 函数是对象*/
function sayHi(x) {
alert("Hi, " + x + "!");
}
sayHi.text = "Hello World";
sayHi["text2"] = "Hello World... again";
alert(sayHi["text"]); // displays "Hello World!"
alert(sayHi.text2); // displays "Hello World... again."
/**作为对象,函数还可以赋给变量、作为参数传递给其他函数、作为其他函数的值返回,并可以作为对象的属性或数组的元素进行存储等等*/
// 函数还可以赋给变量
var greet = function(x) {
alert("Hello, " + x);
};
greet("MSDN readers");
// 函数作为参数传递给其他函数
function square(x) {
return x * x;
}
function operateOn(num, func) {
return func(num);
}
// displays 256
alert(operateOn(16, square));
// 函数作为其他函数的值返回
function makeIncrementer() {
return function(x) { return x + 1; };
}
var inc = makeIncrementer();
// displays 8
alert(inc(7));
// 函数作为数组的元素进行存储
var arr = [];
arr[0] = function(x) { return x * x; };
arr[1] = arr[0](2);
arr[2] = arr[0](arr[1]);
arr[3] = arr[0](arr[2]);
// displays 256
alert(arr[3]);
// 函数作为对象的属性
var obj = { "toString" : function() { return "This is an object."; } };
// calls obj.toString()
alert(obj);