Function(內置對象)
FunctionistheobjectfromwhichJavaScriptfunctionsarederived.Functionsarefirst-classdatatypesinJavaScript,sotheymaybeassignedtovariablesandpassedtofunctionsasyouwouldanyotherpieceofdata.Functionsare,ofcourse,referencetypes.
TheFunctionobjectprovidesbothstaticpropertieslikelengthandpropertiesthatconveyusefulinformationduringtheexecutionofthefunction,forexample,thearguments[]array.
Constructor
varinstanceName=newFunction([arg1[,arg2[,...]],]body);
Thebodyparameterisastringcontainingthetextthatmakesupthebodyofthefunction.TheoptionalargN'sarethenamesoftheformalparametersthefunctionaccepts.Forexample:
varmyAdd=newFunction("x","y","returnx+y");
varsum=myAdd(17,34);
Properties
arguments[]Animplicitlyfilledandimplicitlyavailable(directlyusableas"arguments"fromwithinthefunction)arrayofparametersthatwerepassedtothefunction.Thisvalueisnullifthefunctionisnotcurrentlyexecuting.(IE4+(JScript2.0+),MOZ,N3+(JavaScript1.1+),ECMAEdition1)
arguments.calleeReferencetothecurrentfunction.Thispropertyisdeprecated.(N4+,MOZ,IE5.5+)
arguments.callerReferencetothefunctionthatinvokedthecurrentfunction.Thispropertyisdeprecated.(N3,IE4+)
arguments.lengthThenumberofargumentsthatwerepassedtothefunction.(IE4+(JScript2.0+),MOZ,N3+(JavaScript1.1+),ECMAEdition1)
arityNumericvalueindicatinghowmanyargumentsthefunctionexpects.Thispropertyisdeprecated.(N4+,MOZ)
callerReferencetothefunctionthatinvokedthecurrentfunctionornullifcalledfromtheglobalcontext.(IE4+(JScript2.0+),MOZ,N3+)
constructorReferencetotheconstructorobjectthatcreatedtheobject.(IE4+(JScript2.0+),N3+(JavaScript1.1+),ECMAEdition1)
lengthThenumberofargumentsthefunctionexpectstobepassed.(IE4+(JScript2.0+),N3+(JavaScript1.1+),ECMAEdition1)
prototypeReferencetotheobject'sprototype.(IE4+(JScript2.0+),N3+(JavaScript1.1+),ECMAEdition1)
Methods
apply(thisArg[,argArray])InvokesthefunctionwiththeobjectreferencedbythisArgasitscontext(soreferencestothisinthefunctionreferencethisArg).TheoptionalparameterargArraycontainsthelistofparameterstopasstothefunctionasitisinvoked.(IE5.5+(JScript5.5+),N4.06+(JavaScript1.3+),MOZ,ECMAEdition3)
call(thisArg[,arg1[,arg2[,...]]])InvokesthefunctionwiththeobjectreferencedbythisArgasitscontext(soreferencestothisinthefunctionreferencethisArg).TheoptionalparametersargNarepassedtothefunctionasitisinvoked.(IE5.5+(JScript5.5+),N4.06+(JavaScript1.3+),MOZ,ECMAEdition3)
toString()Returnsthestringversionofthefunctionsource.Thebodyofbuilt-inandbrowserobjectswilltypicallyberepresentedbythevalue"[nativecode]".(IE4+(JScript2.0+),N3+(JavaScript1.1+),MOZ,ECMAEdition1)
valueOf()Returnsthestringversionofthefunctionsource.Thebodyofbuilt-inandbrowserobjectswilltypicallyberepresentedbythevalue"[nativecode]".(IE4+(JScript2.0+),N3+(JavaScript1.1+),MOZ,ECMAEdition1)
Support
SupportedinIE4+(JScript2.0+),N3+(JavaScript1.1+),MOZ,ECMAScriptEdition1.
Notes
Generalexamplesoffunctionsarefoundthroughoutthebook,butseeChapter5forexamplesoftheadvancedaspectsoffunctionsandtheFunctionobject.