js中arguments,callee,callee.caller,apply,call的区别

面试中经常会问到这几者区别,在此记录一下:
1.arguments是一个对象,是函数的一个特性,只有在函数内才具有这个特性,在函数外部不能使用。
例子:

function test(){
  console.log(arguments);
}
test()
console.log(typeof arguments);//"undefined"

函数内的arguments输出结果为:


js中arguments,callee,callee.caller,apply,call的区别_第1张图片
image.png

2.callee,caller
callee:表示当前正在使用的函数,例如arguments.callee在上例中表示test(由上图可以看出来)
caller:表示当前函数的调用者,如果在最顶层,那么就为null,如执行test(),则为null,test2()则为test2

function test(){
  console.log(arguments.callee);
 console.log(arguments.callee.caller);
}
function test2(){
  test();
}
test();
test2();
js中arguments,callee,callee.caller,apply,call的区别_第2张图片
image.png

3.apply和call
是函数原型的一个方法,调用者的类型必须势函数。官方解释:应用某一对象的一个方法,用另一个对象替换当前对象。简单讲,就是对象置换。
apply和call的区别:方法传递的参数不同
fn.call(this,arg1,agr2,arg3,...) == fn.apply(this,arguments) ==this.fun(arg1, arg2, arg3,...)

你可能感兴趣的:(js中arguments,callee,callee.caller,apply,call的区别)