arguments对象支持哪些属性

lea*_*ner 2 javascript node.js

我在NodeJS的一次采访中被问到这个问题,

arguments对象支持哪些属性.

a) caller
b) callee
c) length
d) All
Run Code Online (Sandbox Code Playgroud)

当我用Google搜索时,我发现参数对象的所有3个属性都存在.

但是,如果我尝试使用示例程序对此进行测试,我会发现只存在Length属性.

这是我的示例程序:

var events = 'HelloWorld'

abc(events);
function abc(args) {
    console.log(args.charAt(1))   
    console.log(args.callee);
    console.log(args.caller);
    console.log(args.length);
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

e
undefined
undefined
10
Run Code Online (Sandbox Code Playgroud)

因此基于以上输出,只有length是有效属性,但基于以上所有3都是有效属性.那么对此的正确答案是什么?

Buc*_*ket 5

您的范围变量args和局部变量Function.arguments是两个非常不同的东西.在您的函数中abc(args),args是作用域变量,它将是您传入其调用的任何内容.

arguments但是,是一个类似于本地数组的变量,可以在每个函数调用中访问,并与传递给函数的值相对应.例如:

function foo(args) {
    console.log(args);
    console.log(arguments[0]);
    console.log(arguments[1]);
    console.log(arguments[2]);
}

foo("bar", "baz", 123, 456);
Run Code Online (Sandbox Code Playgroud)

这将输出:

> "bar"
> "bar"
> "baz"
> 123
Run Code Online (Sandbox Code Playgroud)

尽管此函数只接受一个参数,args但局部变量arguments仍然存在,并且它表示传递给此函数的所有参数.这样我们仍然可以找到第二,第三和第四个参数的值,即使它们未被声明为函数范围的一部分.

您看到的问题是,您尝试访问Function.arguments范围变量中的属性args,当两者完全是不同的变量时.如果要访问这些属性,请arguments改为引用:

var events = 'HelloWorld'
abc(events);

function abc(args) { 
    console.log(args.charAt(1));   
    console.log(arguments.callee);
    // console.log(arguments.caller); //DEPRECATED
    console.log(arguments.length);
}
Run Code Online (Sandbox Code Playgroud)

  • 可能值得指出的是,"arguments.caller"已被贬低到过时的程度.我认为它不适用于最新版本的节点. (2认同)