昨天与突然想起一个参数callee, 放狗搜了半天,最后感谢kejun给的developer.mozilla.org.呵呵 , 主要是想在JS完美实现可变参数问>题。
首先介绍下Arguments对象,以下摘自core javascript 1.5 reference
The arguments object is a local variable available within all functions; arguments as a property of Function can no longer be used. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.
恩,很明显,通过argument我们可以很方便的实现可变参数函数
var add = function(){
var sum = 0;
for each (var item in arguments){
sum += item;
}
document.write(sum); // 一个任意数目Integer求和的简单例子
}
当然PHP和C++也有类似,PHP中有func_get_args, func_get_arg, func_num_args 等系列参数
C++中有va_list, va_start, va_end 当然,C/C++中的又比较复杂了,等我有时间研究研究再说。 :)
最后我要通过arguments对象的callee属性来实现js的匿名函数递归。。
对于callee,以下摘自core js 1.5 reference
arguments.callee allows anonymous functions to refer to themselves, which is necessary for recursive anonymous functions.
可见,callee主要就是用来做匿名recursive的,嘿嘿,例子如下
function factorial(n){
return function(n){
if(n == 1) return 1 ;
else return n * arguments.callee(n-1);
};
}
上面的callee引用了匿名的阶乘函数本身。 使用factorial()(8)调用求8的阶乘,返回40320..
恩,昨天终于弄清了ecma 262 是什么东东, 以及又发现一些很有趣的东西在js1.6 1.8 :)
首先介绍下Arguments对象,以下摘自core javascript 1.5 reference
The arguments object is a local variable available within all functions; arguments as a property of Function can no longer be used. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.
恩,很明显,通过argument我们可以很方便的实现可变参数函数
var add = function(){
var sum = 0;
for each (var item in arguments){
sum += item;
}
document.write(sum); // 一个任意数目Integer求和的简单例子
}
当然PHP和C++也有类似,PHP中有func_get_args, func_get_arg, func_num_args 等系列参数
C++中有va_list, va_start, va_end 当然,C/C++中的又比较复杂了,等我有时间研究研究再说。 :)
最后我要通过arguments对象的callee属性来实现js的匿名函数递归。。
对于callee,以下摘自core js 1.5 reference
arguments.callee allows anonymous functions to refer to themselves, which is necessary for recursive anonymous functions.
可见,callee主要就是用来做匿名recursive的,嘿嘿,例子如下
function factorial(n){
return function(n){
if(n == 1) return 1 ;
else return n * arguments.callee(n-1);
};
}
上面的callee引用了匿名的阶乘函数本身。 使用factorial()(8)调用求8的阶乘,返回40320..
恩,昨天终于弄清了ecma 262 是什么东东, 以及又发现一些很有趣的东西在js1.6 1.8 :)