日期:2014-05-16 浏览次数:20449 次
在很多语言中,函数(Java里面成为方法)和对象时截然不同的两种东西。函数被定义为对象的动作,或者是全局的(像在C++中的main函数一样)。但是在JavaScript中,函数和对象的界限却显得不那么明显。
1. 函数的定义
JavaScript中有很多种定义函数的方法:
function hello() { alert("Hello!"); }
var hello1 = function() { alert("Hello!"); };
var hello2 = new Function("", "alert('Hello!');");
hello();
hello1();
hello2();
?hello();
hello1(); // error
function hello() { alert("Hello!"); }
var hello1 = function() { alert("Hello!"); };
?function sayHelloTo(name) {
alert("Hello, " + name);
}
var sayHelloTo1 = new Function("name", "alert('Hello, ' + name)");
?function sum2(a, b) {
alert(a + b);
}
sum2(1); // NaN
sum2(1, 2); // 3
sum2(1, 3, 5); // 4
?function sum() {
var total = 0;
for(var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
alert(total);
}
sum(1, 2);
sum(1, 2, 3);
?arguments.length其实可以看成是实参个数,还有一个方法是看形参个数sum.length。。function sum(n) {
if(n <= 1) {
return 1;
}
return n + arguments.callee(n - 1); // 递归调用自身
}
alert(sum(100));
?function hello() {
alert("Hello!");
}
hello.name = "Tom"; // 添加属性
alert(hello["name"]);
delete hello.name; // 删除属性
alert(hello.name);
// 赋值给变量
var hello1 = function() { alert("hello1"); };
hello1();
// 作为数组元素
function show(x) { alert(x); }
var arr = [show];
arr[0](5);
// 作为函数的参数
function callFunc(func) {
func();
}
callFunc(function() {
alert("Inner Function.");
});
// 作为函数的返回值
function show() {
return function(n) {
alert("number is " + n);
};
}
show()(10);
?