`
luck332
  • 浏览: 84880 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

arguments,callee&caller

阅读更多

 

arguments,callee&caller测试

关键字:arguments,callee,caller
arguments:表示传入函数的参数
callee:表示函数和函数主体的语句
caller:表示调用该函数的函数
arguments

该对象代表正在执行的函数和调用它的函数的参数。
caller
返回一个对函数的引用,该函数调用了当前函数。
functionName.caller
functionName 对象是所执行函数的名称。
说明
对于函数来说,caller属性只有在函数执行时才有定义。如果函数是由顶层调用的,那么 caller包含的就是 null 。如果在字符串上下文中使用 caller 属性,那么结果和functionName.toString一样,也就是说,显示的是函数的反编译文本。
callee

返回正被执行的 Function 对象,也就是所指定的Function 对象的正文。

[function.]arguments.callee
可选项 function 参数是当前正在执行的 Function 对象的名称。

说明

callee 属性的初始值就是正被执行的 Function 对象。

callee 属性是 arguments对象的一个成员,它表示对函数对象本身的引用,这有利于匿名
函数的递归或者保证函数的封装性,例如下边示例的递归计算1到n的自然数之和。而该属性
仅当相关函数正在执行时才可用。还有需要注意的是callee拥有length属性,这个属性有时候
用于验证还是比较好的。arguments.length是实参长度,arguments.callee.length是
形参长度,由此可以判断调用时形参长度是否和实参长度一致。

 

<script type='text/javascript'>
function test(x,y,z)
{
alert("实参长度:"+arguments.length);
alert("形参长度:"+arguments.callee.length);
alert("形参长度:"+test.length);
alert(arguments[ 0 ])
alert(test[ 0 ]) // undefined 没有这种用法

}

//test(1,2,3);
test(1,2,3,4);

/*
* arguments不是数组(Array类)
*/
Array.prototype.selfvalue = 1 ;
function testAguments() {
alert( " arguments.selfvalue= " + arguments.selfvalue);
}
alert("Array.sefvalue="+new Array().selfvalue);
testAguments();

/**/ /*
* 演示函数的caller属性.
* 说明:(当前函数).caller:返回一个对函数的引用,该函数调用了当前函数
*/

function callerDemo() {
if (callerDemo.caller) {
var a = callerDemo.caller.arguments[ 0 ];
alert(a);
} else {
alert( " this is a top function " );
}
}
function handleCaller() {
callerDemo();
}

callerDemo();
handleCaller("参数1","参数2");


/**/ /*
* 演示函数的callee属性.
* 说明:arguments.callee:初始值就是正被执行的 Function 对象,用于匿名函数
*/
function calleeDemo() {
alert(arguments.callee);
}
calleeDemo();
(function(arg0,arg1){alert("形数数目为:"+arguments.callee.length)})();


/**/ /*
* 演示apply,call函数的用法
* 说明:作用都是将函数绑定到另外一个对象上去运行,两者仅在定义参数方式有所区别:
* apply(thisArg,argArray);
* call(thisArg[,arg1,arg2…] ]);
* 即所有函数内部的this指针都会被赋值为thisArg
*/

function ObjectA() {
alert( " 执行ObjectA() " );
alert(arguments[ 0 ]);
this .hit = function (msg) {alert(msg)}
this .info = " 我来自ObjectA "
}

function ObjectB() {
alert( " 执行ObjectB() " );
// 调用ObjectA()方法,同时ObjectA构造函数中的所有this就会被ObjectB中的this替代
ObjectA.apply( this ,arguments); // ObjectA.call(this);
alert( this .info);
}
ObjectB('参数0');


var value = " global 变量 " ;
function Obj() {
this .value = " 对象! " ;
}
function Fun1() {
alert( this .value);
}
Fun1();
Fun1.apply(window);
Fun1.apply(new Obj());

</script>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics