gpt4 book ai didi

Javascript:参数随着进一步的应用处理而改变

转载 作者:行者123 更新时间:2023-11-29 22:28:00 25 4
gpt4 key购买 nike

    function Foo(){

}
Foo.prototype={
method1:function(o){
console.log(o);
}
,shorthand:function(){
if(!arguments.length || typeof arguments[0]=='undefined') {
arguments[0]={};
}
arguments[0].bar='test';
return this.method1.apply(this,arguments);
}
}

var instance=new Foo();
instance.shorthand();

console.log(o); // returns undefined

一段时间后我发现,为数组分配参数可以解决这个问题。

arguments=[{bar:'test'}];

我发现,arguments 毕竟不是数组,也不是半数组。好吧,它没有推送方法。

为什么这样做(我的意思是返回未定义)?它是出于某种目的而制作的吗?

最佳答案

您已经看到 arguments 不是数组,而只是“类数组”。它是一个具有数字键和 length 属性的普通对象:

arguments object

你的代码

arguments[0]={};
arguments[0].bar='test';

确实以某种方式起作用。

但因为它不是数组,所以length 属性没有更新。所以尽管你添加了一个属性,length 仍然是 0:

arguments length 0

现在,我不知道 apply 的实现,但我假设它使用 length 属性迭代“数组”中的所有元素。如果长度为零,它不会向函数传递任何参数,因此 o 在这种情况下确实是 undefined

如果你添加

arguments.length = 1;

然后它works as you expected .

将数组分配给 arguments 只会覆盖对象,将元素分配给数组会更新已知的 length

关于Javascript:参数随着进一步的应用处理而改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8399162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com