JavaScript 之arguments、caller 和 callee 介绍
2015-10-21 09:50
357 查看
1.前言
arguments, caller , callee 是什么?在javascript 中有什么样的作用?本篇会对于此做一些基本介绍。
2. arguments
arguments: 在函数调用时, 会自动在该函数内部生成一个名为 arguments的隐藏对象。 该对象类似于数组, 但又不是数组。可以使用[]操作符获取函数调用时传递的实参。[html] view
plaincopy
<!--by oscar999 2013-1-16-->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Arguments Test</title>
</head>
<body>
<script>
function testArg()
{
alert("real parameter count: "+arguments.length);
for(var i = 0; i < arguments.length; i++)
{
alert(arguments[i]);
}
}
testArg(11); //count: 1
testArg('hello','world'); // count: 2
</script>
</body>
</html>
看上去很简单。 需要注意的是 argument 保存的实参的信息。
上面有说, arguments 不是一个数组,何以见得? 执行以下部分就可以知道了
[javascript] view
plaincopy
(function () {
alert(arguments instanceof Array); // false
alert(typeof(arguments)); // object
})();
对于以上立即执行函数写法不清楚的话, 可以参考
http://blog.csdn.net/oscar999/article/details/8507919
只有函数被调用时,arguments对象才会创建,未调用时其值为null:
[javascript] view
plaincopy
alert(new Function().arguments);//return null
arguments 的完整语法如下:
[function.]arguments
参数function :选项。当前正在执行的 Function 对象的名字。 n :选项。要传递给 Function 对象的从0开始的参数值索引。
3. caller
在一个函数调用另一个函数时,被调用函数会自动生成一个caller属性,指向调用它的函数对象。如果该函数当前未被调用,或并非被其他函数调用,则caller为null。[javascript] view
plaincopy
<script>
function testCaller() {
var caller = testCaller.caller;
alert(caller);
}
function aCaller() {
testCaller();
}
aCaller();
4. callee
当函数被调用时,它的arguments.callee对象就会指向自身,也就是一个对自己的引用。由于arguments在函数被调用时才有效,因此arguments.callee在函数未调用时是不存在的(即null.callee),且解引用它会产生异常。
[javascript] view
plaincopy
<script>
function aCallee(arg) {
alert(arguments.callee);
}
function aCaller(arg1, arg2) {aCallee();}
aCaller();
原文转载于:http://blog.csdn.net/oscar999/article/details/8511335
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- IE8开发人员工具教程(二)
- 在flex中执行一个javascript方法的简单方式
- Flex结合JavaScript读取本地路径的方法
- PowerShell中执行Javascript的方法示例
- javascript asp教程第六课-- response方法
- javascript asp教程More About Recordsets