简单了解JavaScript arguement原理及作用
问题
varlength=10;
functionfn(){
alert(this.length);
}
varobj={
length:5,
method:function(fn){
arguments[0]()
}
}
obj.method(fn);//1
这段代码中的arguments[0]()是第一个参数?带一对小括号是什么意思?
理解
我们可以先从最后调用obj.method(fn)开始理解。
1.obj是对象,method()是obj的方法,fn是method()的参数,fn是函数的名,他引用对应的函数。arguments是JavaScript的一个内置对象。
AnArray-likeobjectcorrespondingtotheargumentspassedtoafunction.
Theargumentsobjectisalocalvariableavailablewithinallfunctions;argumentsasapropertyofFunctioncannolongerbeused.Description:Youcanrefertoafunction‘sargumentswithinthefunctionbyusingtheargumentsobject.Thisobjectcontainsanentryforeachargumentpassedtothefunction,thefirstentry'sindexstartingat0.
2.arguments是用来取得method(fn)的参数的类数组,在这里也就是fn,即arguments[0]===fn或arguments.0===fn(0就是arguments的一个属性)。所以arguments[0]()就等于fn()。
是不是到这里要开始风中凌乱了,this.length究竟是指向那个对象呢?可以这样理解:
arguments={
0:fn,//也就是functon(){alert(this.length)}
1:第二个参数,//没有
2:第三个参数,//没有
...,
length:1//只有一个参数
}
最后,这个1就是arguments.length,也就是本函数参数的个数。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。