转:全面理解javascript的caller,callee,call,apply概念
2012-09-16 20:08 youxin 阅读(322) 评论(0) 编辑 收藏 举报javascript中函数的隐含参数:arguments
Arguments
该对象代表正在执行的函数和调用它的函数的参数。
[function.]arguments[n]
参数
function:选项。当前正在执行的 Function对象的名字。
n:选项。要传递给 Function对象的从0开始的参数值索引。
说明
//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'; } }
ArgTest(3,2,1);
document.write('<br/>'+new Array().selfvalue);//输出1
function testArguments()
{
document.writeln(arguments.selfvalue); //显示undefined
}
testArguments();
alert(arguments instanceof Object);
caller
返回一个对函数的引用,该函数调用了当前函数。(即返回调用此函数的函数)functionName.caller
functionName 对象是所执行函数的名称。
说明
对于函数来说,caller 属性只有在函数执行时才有定义。如果函数是由顶层调用的,那么 caller 包含的就是 null 。如果在字符串上下文中使用 caller 属性,那么结果和 functionName.toString 一样,也就是说,显示的是函数的反编译文本。
下面的例子说明了 caller 属性的用法:
下面的例子说明了 caller 属性的用法: function callerDemo() { if(callerDemo.caller) { var a=callerDemo.caller; document.write('<br/>'+a); } else { document.write('<br/>'+"this is a top function"); } } callerDemo(); function handleCaller(){ callerDemo();//返回正被执行的 Function 对象,也就是所指定的 Function 对象的正文 } handleCaller(); output: this is a top function function handleCaller(){ callerDemo(); }
返回正被执行的 Function 对象,也就是所指定的 Function 对象的正文。
[function.]arguments.callee
可选项 function 参数是当前正在执行的 Function 对象的名称。
说明
callee 属性的初始值就是正被执行的 Function 对象。
callee 属性是 arguments 对象的一个成员,它表示对函数对象本身的引用,这有利于匿名
函数的递归或者保证函数的封装性,例如下边示例的递归计算1到n的自然数之和。而该属性
仅当相关函数正在执行时才可用。还有需要注意的是callee拥有length属性,这个属性有时候
用于验证还是比较好的。arguments.length是实参长度,arguments.callee.length是
形参长度,由此可以判断调用时形参长度是否和实参长度一致。
//打印其自身 function calleeDemo() { document.write('<br/>'+arguments.callee); } calleeDemo(); //用于验证参数 function calleeLengthDemo(arg1,arg2) { if(arguments.length==arguments.callee.length) { document.write('<br/>'+'验证形参和实参长度正确!'); } else { document.write("<br/>实参长度:"+arguments.length); document.write('<br/>形参长度'+arguments.callee.length); } }
'+arguments.callee); }
实参长度:4
形参长度2
if(n==1) return 1;
else
return n+sum(n-1);
}
document.write(sum(100));
一个全局变量,不能很好的体现出是调用自身,这时使用callee会是一个比较好的方法。
if(n==1) return 1;
else
return n+arguments.callee(n-1);
}
document.write(sum(100));
apply(thisArg,argArray);
call(thisArg[,arg1,arg2…] ]);
即所有函数内部的this指针都会被赋值为thisArg,这可实现将函数作为另外一个对象的方法运行的目的
apply的说明
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisArg任何一个参数,那么 Global 对象将被用作 thisArg,
并且无法被传递任何参数。
call的说明
call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisArg指定的新对象。
如果没有提供 thisArg参数,那么 Global 对象被用作 thisArg
相关技巧:
函数(类)就具备了另一个函数(类)的方法或者是属性,这也可以称之为“继承”。看下面示例:
{
this.member='memmber';
this.method=function(){
document.write(this.member);
}
}
function extend(){
base.call(this);
document.write('<br/><br/>'+member);
}
extend();
顺便提一下,在javascript框架prototype里就使用apply来创建一个定义类的模式,
其实现代码如下:
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
解析:从代码看,该对象仅包含一个方法:Create,其返回一个函数,即类。但这也同时是类的
构造函数,其中调用initialize,而这个方法是在类创建时定义的初始化函数。通过如此途径,
就可以实现prototype中的类创建模式
示例:
vehicle.prototype={
initialize:function(type){
this.type=type;
}
showSelf:function(){
alert("this vehicle is "+ this.type);
}
}
The main difference is that apply
lets you invoke the function with arguments as an array; call
requires the parameters be listed explicitly.
apply和call的主要区别在于call必须显示列出参数,而apply可以调用数组。
Pseudo syntax:
theFunction.apply(valueForThis, arrayOfArgs)
theFunction.call(valueForThis, arg1, arg2, ...)
mozilla解释:
Function.prototype.apply method
Calls a function with a given this
value and arguments
provided as an array.
thisArg
- The value of
this
provided for the call tofun
. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code,null
andundefined
will be replaced with the global object, and primitive values will be boxed.
argsArray
- An array like object, specifying the arguments with which
fun
should be called, ornull
or undefined if no arguments should be provided to the function. - 当第一个参数 为null 或undefined时,将是JS执行环境的全局变量。浏览器中是window,其它环境(如node)则是global。
-
function func()
{
document.write('<br/>'+this);
}
func.call(1);func(null); //global 或window
func(undefined); //global 或window严格模式下情况又有所不同,ES3比较宽容尽量去揣测代码意图。ES5严格模式(ie6/7/8/9除外)则不再揣测,给
call/apply传入的任何参数不再转换。如下
'use strict'
function
fun() {
alert(
this
);
}
fun.call(
null
)
// null
fun.call(undefined)
// undefined
call/apply用来改变函数的执行上下文(this),它们的第一个参数thisArg是个对象,即作为函数内的this。
多数时候你传啥函数内就是啥。仅以call示例
function fun() { alert(this); } fun.call(1); fun.call('a'); fun.call(true); fun.call({name:'jack'});
分别弹出“1”、“a”、“true”、“[object Object]”。
var obj = { yes: function(){ // this == obj this.val = true; }, no: function(){ this.val = false; } }; // We see that there is no val property in the 'obj' object alert( obj.val == null ); // We run the yes function and it changes the val property // associated with the 'obj' object obj.yes(); alert( obj.val == true ); // However, we now point window.no to the obj.no method and run it 把window.no指向obj.no并执行之 window.no = obj.no; window.no(); // This results in the obj object staying the same (as the context was // switched to the window object) alert( obj.val == true ); // and window val property getting updated. alert( window.val == false );
function changeColor( color ) {
this.style.color = color;
}
// Calling it on the window object, which fails, since it doesn't
// have a style object
changeColor( "white" ); 在window对象中调用此函数会失败,因为widnow没有style属性。
// Find the element with an ID of main
var main = document.getElementById("main");
// Set its color to black, using the call method
// The call method sets the context with the first argument
// and passes all the other arguments as arguments to the function
changeColor.call( main, "black" ); 、、main颜色会是black
// A function that sets the color on the body element
function setBodyColor() {
// The apply method sets the context to the body element
// with the first argument, the second argument is an array
// of arguments that gets passed to the function
changeColor.apply( document.body, arguments );
}
// Set the background color of the body to black
setBodyColor( "black" );
{
changeColor.call(document.body,arguments[0]);
}
setBodyColor('lime');
在js中,你的代码总有一个上下文对象(代码处在该对象内)。这是oo的常见特点,但其他语言没有js发挥的那么极致。
yes: function(){
// this == obj
this.val = true;
},
no: function(){
this.val = false;
}
};
// We see that there is no val property in the 'obj' object
alert( obj.val == null );
// We run the yes function and it changes the val property
// associated with the 'obj' object
obj.yes();
alert( obj.val == true );
// However, we now point window.no to the obj.no method and run it 把window.no指向obj.no并执行之
window.no = obj.no;
window.no();
// This results in the obj object staying the same (as the context was
// switched to the window object)
alert( obj.val == true );
// and window val property getting updated.
alert( window.val == false );
function changeColor( color ) {
this.style.color = color;
}
// Calling it on the window object, which fails, since it doesn't
// have a style object
changeColor( "white" ); 在window对象中调用此函数会失败,因为widnow没有style属性。
// Find the element with an ID of main
var main = document.getElementById("main");
// Set its color to black, using the call method
// The call method sets the context with the first argument
// and passes all the other arguments as arguments to the function
changeColor.call( main, "black" ); 、、main颜色会是black
// A function that sets the color on the body element
function setBodyColor() {
// The apply method sets the context to the body element
// with the first argument, the second argument is an array
// of arguments that gets passed to the function
changeColor.apply( document.body, arguments );
}
// Set the background color of the body to black
setBodyColor( "black" );
{
changeColor.call(document.body,arguments[0]);
}
setBodyColor('lime');