全面理解javascript的caller,callee,call,apply概念(修改版)
原文转自 http://www.cnblogs.com/sunwangji/archive/2006/08/21/482341.html,适当做了修改
在提到上述的概念之前,首先想说说javascript中函数的隐含参数:arguments
Arguments
该对象代表正在执行的函数和调用它的函数的参数。
[function.]arguments[n]
参数
function :选项。当前正在执行的 Function 对象的名字。
n :选项。要传递给 Function 对象的从0开始的参数值索引。
说明
Arguments是进行函数调用时,除了指定的参数外,还另外创建的一个隐藏对象。Arguments是一个类似数组但不是数组的对象,说它类似数组是因为其具有数组一样的访问性质及方式,可以由arguments[n]来访问对应的单个参数的值,并拥有数组长度属性length。还有就是arguments对象存储的是实际传递给函数的参数,而不局限于函数声明所定义的参数列表,而且不能显式创建 arguments 对象。arguments 对象只有函数开始时才可用。下边例子详细说明了这些性质:
//arguments 对象的用法。 function ArgTest(a, b){ var i, s = "The ArgTest function expected "; var numargs = arguments.length; // 获取被传递参数的数值。 var expargs = ArgTest.length; // 获取期望参数的数值。 if (expargs < 2) s += expargs + " argument. "; else s += expargs + " arguments. "; if (numargs < 2) s += numargs + " was passed."; else s += numargs + " were passed."; s += "\n\n"; for (i =0 ; i < numargs; i++){ // 获取参数内容。 s += " Arg " + i + " = " + arguments[i] + "\n"; } return(s); // 返回参数列表。 } alert(ArgTest('a1', 'b1'));alert(ArgTest('a2', 'b2', 'c2'));alert(ArgTest('a3'));
Array.prototype.selfvalue = 1;alert('new Array().selfvalue=' + new Array().selfvalue);function testAguments(){ alert(arguments.selfvalue); }testAguments('a4');
alert(arguments instanceof Array);alert(arguments instanceof Object);
function callerDemo() { if (callerDemo.caller) { var a= callerDemo.caller.toString(); alert(a); } else { alert("this is a top function"); }}function handleCaller() { callerDemo();}handleCaller();
//callee可以打印其本身function calleeDemo() { alert(arguments.callee);}//用于验证参数function calleeLengthDemo(arg1, arg2) { if (arguments.length==arguments.callee.length) { alert("验证形参和实参长度正确!"); } else { alert("实参长度:" +arguments.length +"形参长度: " +arguments.callee.length); }}//递归计算var sum = function(n){ if (n <= 1) return 1; else return n + arguments.callee(n - 1);}calleeDemo();calleeLengthDemo('a5', 'b5');calleeLengthDemo('a6');alert(sum(100));
// 继承的演示function Animal() { this.name = "动物"; this.say = function() { window.alert("我是" + this.name); }}function Cat() { Animal.call(this); window.alert(this.name); this.say();}new Animal();new Cat();
var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } }}
var vehicle=Class.create();vehicle.prototype={ initialize:function(type){ this.type=type; } showSelf:function(){ alert("this vehicle is "+ this.type); }}var moto=new vehicle("Moto");moto.showSelf();