方法定義- JavaScript

文章推薦指數: 80 %
投票人數:10人

自ECMAScript 2015 開始,引入了一種於物件初始器(objects initializers)中定義方法的簡短語法。

是一個將函式指派予方法名稱的簡便方式。

SkiptomaincontentSkiptosearchSkiptoselectlanguage給開發者的網頁技術文件JavaScriptJavaScript參考文件Functions方法定義ChangelanguageViewinEnglishThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity.語法說明範例規範瀏覽器相容性參見方法定義 自ECMAScript2015開始,引入了一種於物件初始器(objectsinitializers)中定義方法的簡短語法。

是一個將函式指派予方法名稱的簡便方式。

語法varobj={ property(parameters…){}, *generator(parameters…){}, asyncproperty(parameters…){}, async*generator(parameters…){}, //withcomputedkeys: [property](parameters…){}, *[generator](parameters…){}, async[property](parameters…){}, //comparegetter/settersyntax: getproperty(){}, setproperty(value){} }; 說明這個簡短的語法和在ECMAScript2015引入getter以及setter類似。

請看以下程式碼: varobj={ foo:function(){ /*code*/ }, bar:function(){ /*code*/ } }; 你可以把它縮減為: varobj={ foo(){ /*code*/ }, bar(){ /*code*/ } }; 產生器方法產生器方法(Generatormethod)也可以透過簡短語法定義之。

用的時候: 簡短語法的星號(*)必須放在產生器方法的屬性名前面。

也就是說*g(){}能動但g*(){}不行; 非產生器方法的定義可能不會有yield關鍵字。

也就是說過往的產生器函式動不了、並拋出SyntaxError。

Alwaysuseyieldinconjunctionwiththeasterisk(*). //Usinganamedproperty varobj2={ g:function*(){ varindex=0; while(true) yieldindex++; } }; //Thesameobjectusingshorthandsyntax varobj2={ *g(){ varindex=0; while(true) yieldindex++; } }; varit=obj2.g(); console.log(it.next().value);//0 console.log(it.next().value);//1Async方法Async方法也可以透過簡短語法定義。

//Usinganamedproperty varobj3={ f:asyncfunction(){ awaitsome_promise; } }; //Thesameobjectusingshorthandsyntax varobj3={ asyncf(){ awaitsome_promise; } }; AsyncgeneratormethodsGeneratormethodscanalsobeasync. varobj4={ f:asyncfunction*(){ yield1; yield2; yield3; } }; //Thesameobjectusingshorthandsyntax varobj4={ async*f(){ yield1; yield2; yield3; } };MethoddefinitionsarenotconstructableAllmethoddefinitionsarenotconstructorsandwillthrowaTypeErrorifyoutrytoinstantiatethem. varobj={ method(){} }; newobj.method;//TypeError:obj.methodisnotaconstructor varobj={ *g(){} }; newobj.g;//TypeError:obj.gisnotaconstructor(changedinES2016) 範例Simpletestcasevarobj={ a:'foo', b(){returnthis.a;} }; console.log(obj.b());//"foo" ComputedpropertynamesTheshorthandsyntaxalsosupportscomputedpropertynames. varbar={ foo0:function(){return0;}, foo1(){return1;}, ['foo'+2](){return2;} }; console.log(bar.foo0());//0 console.log(bar.foo1());//1 console.log(bar.foo2());//2規範 Specification Status Comment ECMAScript2015(6thEdition,ECMA-262)Thedefinitionof'Methoddefinitions'inthatspecification. Standard Initialdefinition. ECMAScript2016(ECMA-262)Thedefinitionof'Methoddefinitions'inthatspecification. Standard Changedthatgeneratormethodsshouldalsonothavea[[Construct]]trapandwillthrowwhenusedwithnew. ECMAScript(ECMA-262)Thedefinitionof'Methoddefinitions'inthatspecification. LivingStandard   瀏覽器相容性BCDtablesonlyloadinthebrowser參見 get set Lexicalgrammar Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Dec26,2021,byMDNcontributorsChangeyourlanguageSelectyourpreferredlanguage正體中文(繁體)DeutschEnglish(US)EspañolFrançais日本語한국어Português(do Brasil)Русский中文(简体)ChangelanguageRelatedTopics JavaScript Tutorials: Completebeginners JavaScriptbasics JavaScriptfirststeps JavaScriptbuildingblocks IntroducingJavaScriptobjects JavaScriptGuide Introduction Grammarandtypes Controlflowanderrorhandling Loopsanditeration Functions Expressionsandoperators Numbersanddates Textformatting Regularexpressions Indexedcollections Keyedcollections Workingwithobjects Detailsoftheobjectmodel Usingpromises Iteratorsandgenerators Metaprogramming JavaScriptmodules Intermediate Client-sideJavaScriptframeworks Client-sidewebAPIs Are-introductiontoJavaScript JavaScriptdatastructures Equalitycomparisonsandsameness Closures Advanced Inheritanceandtheprototypechain Strictmode JavaScripttypedarrays MemoryManagement ConcurrencymodelandEventLoop References: Built-inobjects AggregateErrorArrayArrayBufferAsyncFunctionAtomicsBigIntBigInt64ArrayBigUint64ArrayBooleanDataViewDatedecodeURI()decodeURIComponent()encodeURI()encodeURIComponent()Error escape()eval()EvalErrorFinalizationRegistryFloat32ArrayFloat64ArrayFunctionGeneratorGeneratorFunctionglobalThisInfinityInt16ArrayInt32ArrayInt8ArrayInternalErrorIntlisFinite()isNaN()JSONMapMathNaNnullNumberObjectparseFloat()parseInt()PromiseProxyRangeErrorReferenceErrorReflectRegExpSetSharedArrayBufferStringSymbolSyntaxErrorTypedArrayTypeErrorUint16ArrayUint32ArrayUint8ArrayUint8ClampedArrayundefined unescape() uneval()URIErrorWeakMapWeakRefWeakSetWebAssembly Expressions&operators Additionassignment(+=)Addition(+)Assignment(=)asyncfunctionexpressionawaitBitwiseANDassignment(&=)BitwiseAND(&)BitwiseNOT(~)BitwiseORassignment(|=)BitwiseOR(|)BitwiseXORassignment(^=)BitwiseXOR(^)classexpressionCommaoperator(,)Conditional(ternary)operatorDecrement(--)deleteoperatorDestructuringassignmentDivisionassignment(/=)Division(/)Equality(==)Exponentiationassignment(**=)Exponentiation(**)function*expressionFunctionexpressionGreaterthanorequal(>=)Greaterthan(>)Groupingoperator()inoperatorIncrement(++)Inequality(!=)instanceofLeftshiftassignment(<<=)Leftshift(<>=)Rightshift(>>)Spreadsyntax(...)Strictequality(===)Strictinequality(!==)Subtractionassignment(-=)Subtraction(-)superthistypeofUnarynegation(-)Unaryplus(+)Unsignedrightshiftassignment(>>>=)Unsignedrightshift(>>>)voidoperatoryield*yield Statements&declarations asyncfunctionblockbreakclassconstcontinuedebuggerdo...whileemptyexportforawait...offor...infor...offorfunction*functiondeclarationif...elseimport.metaimportlabelletreturnswitchthrowtry...catchvarwhile with Functions TheargumentsobjectArrowfunctionexpressionsDefaultparametersgetterMethoddefinitionsRestparameterssetter Classes ClassstaticinitializationblocksconstructorextendsPrivateclassfeaturesPublicclassfieldsstatic Errors Warning:-file-isbeingassigneda//#sourceMappingURL,butalreadyhasoneTypeError:invalidArray.prototype.sortargumentWarning:08/09isnotalegalECMA-262octalconstantRangeError:radixmustbeanintegerSyntaxError:invalidregularexpressionflag"x"SyntaxError:returnnotinfunctionTypeError:X.prototype.ycalledonincompatibletypeReferenceError:can'taccesslexicaldeclaration`X'beforeinitializationTypeError:can'taccessproperty"x"of"y"TypeError:can'tassigntoproperty"x"on"y":notanobjectTypeError:can'tdefineproperty"x":"obj"isnotextensibleTypeError:property"x"isnon-configurableandcan'tbedeletedTypeError:can'tredefinenon-configurableproperty"x"TypeError:cyclicobjectvalueTypeError:can'taccessdeadobjectSyntaxError:applyingthe'delete'operatortoanunqualifiednameisdeprecatedReferenceError:deprecatedcallerorargumentsusageWarning:expressionclosuresaredeprecatedSyntaxError:"0"-prefixedoctalliteralsandoctalescapeseq.aredeprecatedSyntaxError:Using//@toindicatesourceURLpragmasisdeprecated.Use//#insteadWarning:String.xisdeprecated;useString.prototype.xinsteadWarning:Date.prototype.toLocaleFormatisdeprecatedSyntaxError:testforequality(==)mistypedasassignment(=)?TypeError:settinggetter-onlyproperty"x"SyntaxError:Unexpected'#'usedoutsideofclassbodySyntaxError:identifierstartsimmediatelyafternumericliteralSyntaxError:illegalcharacterTypeError:cannotuse'in'operatortosearchfor'x'in'y'RangeError:invalidarraylengthReferenceError:invalidassignmentleft-handsideTypeError:invalidassignmenttoconst"x"RangeError:invaliddateSyntaxError:for-inloopheaddeclarationsmaynothaveinitializersSyntaxError:adeclarationintheheadofafor-ofloopcan'thaveaninitializerTypeError:invalid'instanceof'operand'x'TypeError:'x'isnotiterableSyntaxError:JSON.parse:badparsingSyntaxError:MalformedformalparameterURIError:malformedURIsequenceSyntaxError:missing]afterelementlistSyntaxError:missing:afterpropertyidSyntaxError:missing}afterfunctionbodySyntaxError:missing}afterpropertylistSyntaxError:missingformalparameterSyntaxError:missing=inconstdeclarationSyntaxError:missingnameafter.operatorSyntaxError:missing)afterargumentlistSyntaxError:missing)afterconditionSyntaxError:missing;beforestatementTypeError:MoreargumentsneededRangeError:repeatcountmustbenon-negativeTypeError:"x"isnotanon-nullobjectTypeError:"x"hasnopropertiesSyntaxError:missingvariablenameTypeError:can'tdeletenon-configurablearrayelementRangeError:argumentisnotavalidcodepointTypeError:"x"isnotaconstructorTypeError:"x"isnotafunctionReferenceError:"x"isnotdefinedRangeError:precisionisoutofrangeError:Permissiondeniedtoaccessproperty"x"TypeError:"x"isread-onlySyntaxError:redeclarationofformalparameter"x"TypeError:ReduceofemptyarraywithnoinitialvalueSyntaxError:"x"isareservedidentifierRangeError:repeatcountmustbelessthaninfinityWarning:unreachablecodeafterreturnstatementSyntaxError:"usestrict"notallowedinfunctionwithnon-simpleparametersInternalError:toomuchrecursionReferenceError:assignmenttoundeclaredvariable"x"ReferenceError:referencetoundefinedproperty"x"SyntaxError:UnexpectedtokenTypeError:"x"is(not)"y"SyntaxError:functionstatementrequiresanameSyntaxError:unterminatedstringliteral Misc JavaScripttechnologiesoverview Lexicalgrammar JavaScriptdatastructures Enumerabilityandownershipofproperties Iterationprotocols Strictmode Transitioningtostrictmode Templateliterals Deprecatedfeatures



請為這篇文章評分?