理解javascript的caller,callee,call,apply概念
在提到上述的概念之前,首先想说说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); // 返回参数列表。}Array.prototype.selfvalue = 1;alert(new Array().selfvalue);function testAguments(){ alert(arguments.selfvalue);}// caller demo {function callerDemo() { if (callerDemo.caller) { var a= callerDemo.caller.toString(); alert(a); } else { alert("this is a top function"); }}function handleCaller() { callerDemo();}//callee可以打印其本身function calleeDemo() { alert(arguments.callee);}//用于验证参数function calleeLengthDemo(arg1, arg2) { if (arguments.length==arguments.callee.length) { window.alert("验证形参和实参长度正确!"); return; } else { alert("实参长度:" +arguments.length); alert("形参长度: " +arguments.callee.length); }}//递归计算var sum = function(n){ if (n <= 0) return 1; else return n +arguments.callee(n - 1)}var sum = function(n){ if (1==n) return 1;else return n + sum (n-1);// 继承的演示function base() { this.member = " dnnsun_Member"; this.method = function() { window.alert(this.member); }}function extend() { base.call(this); window.alert(member); window.alert(this.method);}var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } }}解析:从代码看,该对象仅包含一个方法:Create,其返回一个函数,即类。但这也同时是类的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();