From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- files/id/web/api/abstractworker/index.html | 125 -- files/id/web/api/cachestorage/index.html | 198 -- files/id/web/api/canvas_api/index.html | 172 -- files/id/web/api/console/index.html | 278 --- files/id/web/api/document/createelement/index.html | 225 -- files/id/web/api/document/index.html | 576 ----- files/id/web/api/document/links/index.html | 101 - files/id/web/api/document/write/index.html | 77 - files/id/web/api/element/error_event/index.html | 72 - files/id/web/api/event/currenttarget/index.html | 127 -- files/id/web/api/event/index.html | 149 -- files/id/web/api/event/target/index.html | 90 - files/id/web/api/fetch_api/index.html | 88 - files/id/web/api/index.html | 12 - files/id/web/api/navigator/index.html | 149 -- files/id/web/api/navigator/mediadevices/index.html | 47 - .../id/web/api/navigator/serviceworker/index.html | 101 - files/id/web/api/push_api/index.html | 166 -- files/id/web/api/service_worker_api/index.html | 283 --- .../using_service_workers/index.html | 539 ----- files/id/web/api/serviceworker/index.html | 157 -- files/id/web/api/serviceworkercontainer/index.html | 132 -- .../web/api/serviceworkerregistration/index.html | 245 --- .../pushmanager/index.html | 130 -- files/id/web/api/speechsynthesis/index.html | 151 -- .../api/speechsynthesis/onvoiceschanged/index.html | 74 - files/id/web/api/storage/index.html | 100 - files/id/web/api/webgl_api/index.html | 235 -- files/id/web/api/webrtc_api/index.html | 185 -- files/id/web/api/window/getselection/index.html | 100 - files/id/web/api/window/index.html | 479 ---- files/id/web/api/window/window/index.html | 63 - files/id/web/api/xmlhttprequest/index.html | 200 -- .../xmlhttprequest/using_xmlhttprequest/index.html | 793 ------- .../id/web/css/@font-face/font-display/index.html | 101 - files/id/web/css/@font-face/index.html | 199 -- files/id/web/css/_colon_active/index.html | 143 -- files/id/web/css/background-color/index.html | 149 -- files/id/web/css/css_box_model/index.html | 115 - .../introduction_to_the_css_box_model/index.html | 73 - files/id/web/css/css_selectors/index.html | 154 -- .../index.html | 64 - files/id/web/css/flex-direction/index.html | 155 -- files/id/web/css/index.html | 64 - files/id/web/css/mask-border-width/index.html | 104 - .../media_queries/using_media_queries/index.html | 631 ------ files/id/web/css/reference/index.html | 186 -- files/id/web/css/text-transform/index.html | 307 --- files/id/web/css/type_selectors/index.html | 121 - files/id/web/events/index.html | 2310 -------------------- files/id/web/guide/api/index.html | 26 - files/id/web/guide/graphics/index.html | 49 - files/id/web/guide/html/html5/index.html | 179 -- files/id/web/guide/index.html | 55 - files/id/web/html/element/base/index.html | 154 -- files/id/web/html/element/dialog/index.html | 165 -- files/id/web/html/element/image/index.html | 16 - files/id/web/html/element/index.html | 106 - files/id/web/html/index.html | 97 - files/id/web/http/basics_of_http/index.html | 51 - files/id/web/http/index.html | 81 - files/id/web/http/methods/get/index.html | 73 - files/id/web/http/methods/index.html | 76 - files/id/web/http/overview/index.html | 174 -- .../http/proxy_servers_and_tunneling/index.html | 100 - .../proxy_auto-configuration_pac_file/index.html | 728 ------ files/id/web/http/status/100/index.html | 46 - files/id/web/http/status/200/index.html | 50 - files/id/web/http/status/400/index.html | 39 - files/id/web/http/status/403/index.html | 56 - files/id/web/http/status/404/index.html | 63 - files/id/web/http/status/405/index.html | 44 - files/id/web/http/status/410/index.html | 54 - files/id/web/http/status/500/index.html | 38 - files/id/web/http/status/index.html | 141 -- files/id/web/index.html | 153 -- .../a_re-introduction_to_javascript/index.html | 862 -------- files/id/web/javascript/closures/index.html | 346 --- files/id/web/javascript/data_structures/index.html | 267 --- .../javascript/guide/grammar_and_types/index.html | 649 ------ files/id/web/javascript/guide/index.html | 120 - .../web/javascript/guide/introduction/index.html | 157 -- .../guide/loops_and_iteration/index.html | 331 --- .../javascript/guide/numbers_and_dates/index.html | 377 ---- .../guide/working_with_objects/index.html | 493 ----- files/id/web/javascript/index.html | 116 - .../inheritance_and_the_prototype_chain/index.html | 305 --- .../javascript_technologies_overview/index.html | 88 - .../web/javascript/language_resources/index.html | 136 -- .../id/web/javascript/memory_management/index.html | 187 -- files/id/web/javascript/reference/about/index.html | 86 - .../reference/classes/constructor/index.html | 162 -- .../reference/classes/extends/index.html | 112 - .../id/web/javascript/reference/classes/index.html | 383 ---- .../errors/called_on_incompatible_type/index.html | 69 - .../id/web/javascript/reference/errors/index.html | 12 - .../errors/invalid_array_length/index.html | 78 - .../missing_semicolon_before_statement/index.html | 78 - .../errors/negative_repetition_count/index.html | 45 - .../reference/errors/not_a_codepoint/index.html | 56 - .../reference/errors/not_defined/index.html | 66 - .../errors/property_access_denied/index.html | 47 - .../reference/errors/too_much_recursion/index.html | 70 - .../web/javascript/reference/functions/index.html | 596 ----- .../global_objects/array/concat/index.html | 169 -- .../global_objects/array/filter/index.html | 244 --- .../reference/global_objects/array/from/index.html | 248 --- .../reference/global_objects/array/index.html | 484 ---- .../global_objects/array/isarray/index.html | 144 -- .../reference/global_objects/array/join/index.html | 132 -- .../global_objects/array/length/index.html | 145 -- .../reference/global_objects/array/of/index.html | 129 -- .../reference/global_objects/array/pop/index.html | 134 -- .../global_objects/array/reverse/index.html | 127 -- .../global_objects/array/shift/index.html | 129 -- .../global_objects/array/slice/index.html | 152 -- .../global_objects/array/splice/index.html | 146 -- .../global_objects/array/unshift/index.html | 135 -- .../global_objects/array/values/index.html | 120 - .../global_objects/date/getfullyear/index.html | 88 - .../reference/global_objects/date/index.html | 261 --- .../reference/global_objects/date/now/index.html | 124 -- .../global_objects/date/tojson/index.html | 119 - .../global_objects/date/totimestring/index.html | 125 -- .../reference/global_objects/error/index.html | 231 -- .../reference/global_objects/error/name/index.html | 119 - .../global_objects/function/displayname/index.html | 123 -- .../reference/global_objects/function/index.html | 241 -- .../global_objects/function/length/index.html | 148 -- .../global_objects/function/name/index.html | 191 -- .../javascript/reference/global_objects/index.html | 189 -- .../reference/global_objects/isnan/index.html | 186 -- .../reference/global_objects/json/index.html | 243 -- .../reference/global_objects/json/parse/index.html | 171 -- .../reference/global_objects/map/clear/index.html | 109 - .../reference/global_objects/map/delete/index.html | 114 - .../reference/global_objects/map/index.html | 443 ---- .../reference/global_objects/math/abs/index.html | 145 -- .../reference/global_objects/math/ceil/index.html | 174 -- .../reference/global_objects/math/e/index.html | 81 - .../reference/global_objects/math/floor/index.html | 210 -- .../reference/global_objects/math/index.html | 213 -- .../reference/global_objects/math/ln10/index.html | 81 - .../reference/global_objects/math/max/index.html | 144 -- .../reference/global_objects/math/min/index.html | 150 -- .../reference/global_objects/math/pow/index.html | 53 - .../object/getprototypeof/index.html | 133 -- .../reference/global_objects/object/index.html | 221 -- .../global_objects/object/keys/index.html | 197 -- .../object/preventextensions/index.html | 185 -- .../global_objects/promise/catch/index.html | 127 -- .../reference/global_objects/promise/index.html | 317 --- .../global_objects/promise/reject/index.html | 81 - .../global_objects/promise/resolve/index.html | 140 -- .../global_objects/promise/then/index.html | 132 -- .../reference/global_objects/regexp/index.html | 231 -- .../global_objects/string/charat/index.html | 238 -- .../global_objects/string/concat/index.html | 134 -- .../global_objects/string/fromcharcode/index.html | 143 -- .../global_objects/string/fromcodepoint/index.html | 149 -- .../reference/global_objects/string/index.html | 371 ---- .../global_objects/string/indexof/index.html | 190 -- .../global_objects/string/length/index.html | 126 -- .../global_objects/string/link/index.html | 130 -- .../global_objects/string/split/index.html | 241 -- .../global_objects/string/tolowercase/index.html | 121 - .../global_objects/string/tostring/index.html | 118 - .../global_objects/string/touppercase/index.html | 115 - .../reference/global_objects/typedarray/index.html | 344 --- .../global_objects/typedarray/join/index.html | 114 - files/id/web/javascript/reference/index.html | 48 - .../reference/lexical_grammar/index.html | 670 ------ .../operators/conditional_operator/index.html | 167 -- .../reference/operators/function/index.html | 154 -- .../web/javascript/reference/operators/index.html | 269 --- .../reference/operators/yield/index.html | 109 - .../reference/statements/class/index.html | 171 -- .../reference/statements/do...while/index.html | 101 - .../reference/statements/empty/index.html | 147 -- .../reference/statements/export/index.html | 171 -- .../reference/statements/for...in/index.html | 201 -- .../reference/statements/function/index.html | 233 -- .../web/javascript/reference/statements/index.html | 139 -- files/id/web/mathml/element/index.html | 234 -- files/id/web/mathml/index.html | 76 - files/id/web/reference/api/index.html | 65 - files/id/web/reference/index.html | 49 - files/id/web/security/index.html | 12 - files/id/web/web_components/index.html | 230 -- 189 files changed, 35261 deletions(-) delete mode 100644 files/id/web/api/abstractworker/index.html delete mode 100644 files/id/web/api/cachestorage/index.html delete mode 100644 files/id/web/api/canvas_api/index.html delete mode 100644 files/id/web/api/console/index.html delete mode 100644 files/id/web/api/document/createelement/index.html delete mode 100644 files/id/web/api/document/index.html delete mode 100644 files/id/web/api/document/links/index.html delete mode 100644 files/id/web/api/document/write/index.html delete mode 100644 files/id/web/api/element/error_event/index.html delete mode 100644 files/id/web/api/event/currenttarget/index.html delete mode 100644 files/id/web/api/event/index.html delete mode 100644 files/id/web/api/event/target/index.html delete mode 100644 files/id/web/api/fetch_api/index.html delete mode 100644 files/id/web/api/index.html delete mode 100644 files/id/web/api/navigator/index.html delete mode 100644 files/id/web/api/navigator/mediadevices/index.html delete mode 100644 files/id/web/api/navigator/serviceworker/index.html delete mode 100644 files/id/web/api/push_api/index.html delete mode 100644 files/id/web/api/service_worker_api/index.html delete mode 100644 files/id/web/api/service_worker_api/using_service_workers/index.html delete mode 100644 files/id/web/api/serviceworker/index.html delete mode 100644 files/id/web/api/serviceworkercontainer/index.html delete mode 100644 files/id/web/api/serviceworkerregistration/index.html delete mode 100644 files/id/web/api/serviceworkerregistration/pushmanager/index.html delete mode 100644 files/id/web/api/speechsynthesis/index.html delete mode 100644 files/id/web/api/speechsynthesis/onvoiceschanged/index.html delete mode 100644 files/id/web/api/storage/index.html delete mode 100644 files/id/web/api/webgl_api/index.html delete mode 100644 files/id/web/api/webrtc_api/index.html delete mode 100644 files/id/web/api/window/getselection/index.html delete mode 100644 files/id/web/api/window/index.html delete mode 100644 files/id/web/api/window/window/index.html delete mode 100644 files/id/web/api/xmlhttprequest/index.html delete mode 100644 files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html delete mode 100644 files/id/web/css/@font-face/font-display/index.html delete mode 100644 files/id/web/css/@font-face/index.html delete mode 100644 files/id/web/css/_colon_active/index.html delete mode 100644 files/id/web/css/background-color/index.html delete mode 100644 files/id/web/css/css_box_model/index.html delete mode 100644 files/id/web/css/css_box_model/introduction_to_the_css_box_model/index.html delete mode 100644 files/id/web/css/css_selectors/index.html delete mode 100644 files/id/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html delete mode 100644 files/id/web/css/flex-direction/index.html delete mode 100644 files/id/web/css/index.html delete mode 100644 files/id/web/css/mask-border-width/index.html delete mode 100644 files/id/web/css/media_queries/using_media_queries/index.html delete mode 100644 files/id/web/css/reference/index.html delete mode 100644 files/id/web/css/text-transform/index.html delete mode 100644 files/id/web/css/type_selectors/index.html delete mode 100644 files/id/web/events/index.html delete mode 100644 files/id/web/guide/api/index.html delete mode 100644 files/id/web/guide/graphics/index.html delete mode 100644 files/id/web/guide/html/html5/index.html delete mode 100644 files/id/web/guide/index.html delete mode 100644 files/id/web/html/element/base/index.html delete mode 100644 files/id/web/html/element/dialog/index.html delete mode 100644 files/id/web/html/element/image/index.html delete mode 100644 files/id/web/html/element/index.html delete mode 100644 files/id/web/html/index.html delete mode 100644 files/id/web/http/basics_of_http/index.html delete mode 100644 files/id/web/http/index.html delete mode 100644 files/id/web/http/methods/get/index.html delete mode 100644 files/id/web/http/methods/index.html delete mode 100644 files/id/web/http/overview/index.html delete mode 100644 files/id/web/http/proxy_servers_and_tunneling/index.html delete mode 100644 files/id/web/http/proxy_servers_and_tunneling/proxy_auto-configuration_pac_file/index.html delete mode 100644 files/id/web/http/status/100/index.html delete mode 100644 files/id/web/http/status/200/index.html delete mode 100644 files/id/web/http/status/400/index.html delete mode 100644 files/id/web/http/status/403/index.html delete mode 100644 files/id/web/http/status/404/index.html delete mode 100644 files/id/web/http/status/405/index.html delete mode 100644 files/id/web/http/status/410/index.html delete mode 100644 files/id/web/http/status/500/index.html delete mode 100644 files/id/web/http/status/index.html delete mode 100644 files/id/web/index.html delete mode 100644 files/id/web/javascript/a_re-introduction_to_javascript/index.html delete mode 100644 files/id/web/javascript/closures/index.html delete mode 100644 files/id/web/javascript/data_structures/index.html delete mode 100644 files/id/web/javascript/guide/grammar_and_types/index.html delete mode 100644 files/id/web/javascript/guide/index.html delete mode 100644 files/id/web/javascript/guide/introduction/index.html delete mode 100644 files/id/web/javascript/guide/loops_and_iteration/index.html delete mode 100644 files/id/web/javascript/guide/numbers_and_dates/index.html delete mode 100644 files/id/web/javascript/guide/working_with_objects/index.html delete mode 100644 files/id/web/javascript/index.html delete mode 100644 files/id/web/javascript/inheritance_and_the_prototype_chain/index.html delete mode 100644 files/id/web/javascript/javascript_technologies_overview/index.html delete mode 100644 files/id/web/javascript/language_resources/index.html delete mode 100644 files/id/web/javascript/memory_management/index.html delete mode 100644 files/id/web/javascript/reference/about/index.html delete mode 100644 files/id/web/javascript/reference/classes/constructor/index.html delete mode 100644 files/id/web/javascript/reference/classes/extends/index.html delete mode 100644 files/id/web/javascript/reference/classes/index.html delete mode 100644 files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html delete mode 100644 files/id/web/javascript/reference/errors/index.html delete mode 100644 files/id/web/javascript/reference/errors/invalid_array_length/index.html delete mode 100644 files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html delete mode 100644 files/id/web/javascript/reference/errors/negative_repetition_count/index.html delete mode 100644 files/id/web/javascript/reference/errors/not_a_codepoint/index.html delete mode 100644 files/id/web/javascript/reference/errors/not_defined/index.html delete mode 100644 files/id/web/javascript/reference/errors/property_access_denied/index.html delete mode 100644 files/id/web/javascript/reference/errors/too_much_recursion/index.html delete mode 100644 files/id/web/javascript/reference/functions/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/filter/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/from/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/isarray/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/shift/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/slice/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/splice/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/unshift/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/values/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/getfullyear/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/now/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/tojson/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/totimestring/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/error/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/error/name/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/displayname/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/name/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/isnan/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/json/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/json/parse/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/clear/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/delete/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/abs/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/ceil/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/e/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/floor/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/ln10/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/max/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/min/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/pow/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/keys/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/preventextensions/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/catch/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/reject/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/resolve/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/then/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/regexp/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/charat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/concat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/indexof/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/link/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/split/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/tolowercase/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/tostring/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/touppercase/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/typedarray/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/typedarray/join/index.html delete mode 100644 files/id/web/javascript/reference/index.html delete mode 100644 files/id/web/javascript/reference/lexical_grammar/index.html delete mode 100644 files/id/web/javascript/reference/operators/conditional_operator/index.html delete mode 100644 files/id/web/javascript/reference/operators/function/index.html delete mode 100644 files/id/web/javascript/reference/operators/index.html delete mode 100644 files/id/web/javascript/reference/operators/yield/index.html delete mode 100644 files/id/web/javascript/reference/statements/class/index.html delete mode 100644 files/id/web/javascript/reference/statements/do...while/index.html delete mode 100644 files/id/web/javascript/reference/statements/empty/index.html delete mode 100644 files/id/web/javascript/reference/statements/export/index.html delete mode 100644 files/id/web/javascript/reference/statements/for...in/index.html delete mode 100644 files/id/web/javascript/reference/statements/function/index.html delete mode 100644 files/id/web/javascript/reference/statements/index.html delete mode 100644 files/id/web/mathml/element/index.html delete mode 100644 files/id/web/mathml/index.html delete mode 100644 files/id/web/reference/api/index.html delete mode 100644 files/id/web/reference/index.html delete mode 100644 files/id/web/security/index.html delete mode 100644 files/id/web/web_components/index.html (limited to 'files/id/web') diff --git a/files/id/web/api/abstractworker/index.html b/files/id/web/api/abstractworker/index.html deleted file mode 100644 index cea5a54797..0000000000 --- a/files/id/web/api/abstractworker/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: AbstractWorker -slug: Web/API/AbstractWorker -translation_of: Web/API/AbstractWorker ---- -

{{ APIRef("Web Workers API") }}

- -

Antarmuka AbstractWorker dari abstrak properti Web Workers API  dan method umum untuk semua jenis worker, berupa {{domxref("Worker")}} atau {{domxref("SharedWorker")}}.

- -

Properti

- -

Antarmuka AbstractWorker tidak mewarisi properti apapun.

- -

Event handlers

- -
-
{{domxref("AbstractWorker.onerror")}}
-
Sebuah {{ domxref("EventListener") }} yang dipanggil ketika sebuah {{domxref("ErrorEvent")}} dari tipe error bubbles melalui worker.
-
- -

Method

- -

Antarmuka AbstractWorker tidak menjalankan atau mewarisi method apapun.

- -

Contoh

- -

Catat bahwa anda tidak ingin menggunakan antarmuka AbstractWorker langsung di dalam kode anda — ketika dipanggil, {{domxref("Worker")}} dan {{domxref("SharedWorker")}} mewarisi propertinya. Pada contoh code snippet menunjukan pembuatan objek {{domxref("Worker")}} menggunakan konstruktor {{domxref("Worker.Worker", "Worker()")}} dan penggunakan dari objek:

- -
var myWorker = new Worker("worker.js");
-
-first.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
- -

Contoh lengkapnya, lihat:

- - - -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName("HTML WHATWG", "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2("HTML WHATWG")}}No change from {{SpecName("Web Workers")}}.
{{SpecName("Web Workers", "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2("Web Workers")}}Initial definition.
- -

Kompabilitas Browser

- -
{{CompatibilityTable()}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(4)}}{{CompatGeckoDesktop("1.9.1")}}1010.64
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Dukungan dasar4.4{{CompatGeckoMobile("1.9.1")}}1.0.11011.55.1
-
- -

Lihat Juga

- - - -

 

diff --git a/files/id/web/api/cachestorage/index.html b/files/id/web/api/cachestorage/index.html deleted file mode 100644 index fdcfe56217..0000000000 --- a/files/id/web/api/cachestorage/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: CacheStorage -slug: Web/API/CacheStorage -tags: - - API - - CacheStorage - - Experimental - - Interface - - NeedsTranslation - - Reference - - Service Workers - - ServiceWorker - - TopicStub -translation_of: Web/API/CacheStorage ---- -

{{APIRef("Service Workers API")}}

- -

The CacheStorage interface represents the storage for {{domxref("Cache")}} objects.

- -

The interface:

- - - -

Use {{domxref("CacheStorage.open()")}} to obtain a {{domxref("Cache")}} instance.

- -

Use {{domxref("CacheStorage.match()")}} to check if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the CacheStorage object tracks.

- -

You can access CacheStorage through the global {{domxref("WindowOrWorkerGlobalScope.caches", "caches")}} property.

- -
Note: CacheStorage always rejects with a SecurityError on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu.
- -
Note: {{domxref("CacheStorage.match()")}} is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from {{domxref("CacheStorage.keys()")}}, opening each cache with {{domxref("CacheStorage.open()")}}, and matching the one you want with {{domxref("Cache.match()")}}.
- -

Methods

- -
-
{{domxref("CacheStorage.match()")}}
-
Checks if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the {{domxref("CacheStorage")}} object tracks, and returns a {{jsxref("Promise")}} that resolves to that match.
-
{{domxref("CacheStorage.has()")}}
-
Returns a {{jsxref("Promise")}} that resolves to true if a {{domxref("Cache")}} object matching the cacheName exists.
-
{{domxref("CacheStorage.open()")}}
-
Returns a {{jsxref("Promise")}} that resolves to the {{domxref("Cache")}} object matching the cacheName (a new cache is created if it doesn't already exist.)
-
{{domxref("CacheStorage.delete()")}}
-
Finds the {{domxref("Cache")}} object matching the cacheName, and if found, deletes the {{domxref("Cache")}} object and returns a {{jsxref("Promise")}} that resolves to true. If no {{domxref("Cache")}} object is found, it resolves to false.
-
{{domxref("CacheStorage.keys()")}}
-
Returns a {{jsxref("Promise")}} that will resolve with an array containing strings corresponding to all of the named {{domxref("Cache")}} objects tracked by the {{domxref("CacheStorage")}}. Use this method to iterate over a list of all the {{domxref("Cache")}} objects.
-
- -

Examples

- -

This code snippet is from the MDN sw-test example (see sw-test running live.) This service worker script waits for an {{domxref("InstallEvent")}} to fire, then runs {{domxref("ExtendableEvent.waitUntil","waitUntil")}} to handle the install process for the app. This consists of calling {{domxref("CacheStorage.open")}} to create a new cache, then using {{domxref("Cache.addAll")}} to add a series of assets to it.

- -

In the second code block, we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:

- -
    -
  1. Check whether a match for the request is found in the CacheStorage. If so, serve that.
  2. -
  3. If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using {{domxref("Cache.put")}} (cache.put(event.request, response.clone()).)
  4. -
  5. If this fails (e.g. because the network is down), return a fallback response.
  6. -
- -

Finally, return whatever the custom response ended up being equal to, using {{domxref("FetchEvent.respondWith")}}.

- -
self.addEventListener('install', function(event) {
-  event.waitUntil(
-    caches.open('v1').then(function(cache) {
-      return cache.addAll([
-        '/sw-test/',
-        '/sw-test/index.html',
-        '/sw-test/style.css',
-        '/sw-test/app.js',
-        '/sw-test/image-list.js',
-        '/sw-test/star-wars-logo.jpg',
-        '/sw-test/gallery/bountyHunters.jpg',
-        '/sw-test/gallery/myLittleVader.jpg',
-        '/sw-test/gallery/snowTroopers.jpg'
-      ]);
-    })
-  );
-});
-
-self.addEventListener('fetch', function(event) {
-  event.respondWith(caches.match(event.request).then(function(response) {
-    // caches.match() always resolves
-    // but in case of success response will have value
-    if (response !== undefined) {
-      return response;
-    } else {
-      return fetch(event.request).then(function (response) {
-        // response may be used only once
-        // we need to save clone to put one copy in cache
-        // and serve second one
-        let responseClone = response.clone();
-
-        caches.open('v1').then(function (cache) {
-          cache.put(event.request, responseClone);
-        });
-        return response;
-      }).catch(function () {
-        return caches.match('/sw-test/gallery/myLittleVader.jpg');
-      });
-    }
-  }));
-});
-
- -

This snippet shows how the API can be used outside of a service worker context, and uses the await operator for much more readable code.

- -
// Try to get data from the cache, but fall back to fetching it live.
-async function getData() {
-   const cacheVersion = 1;
-   const cacheName    = `myapp-${ cacheVersion }`;
-   const url          = 'https://jsonplaceholder.typicode.com/todos/1';
-   let cachedData     = await getCachedData( cacheName, url );
-
-   if ( cachedData ) {
-      console.log( 'Retrieved cached data' );
-      return cachedData;
-   }
-
-   console.log( 'Fetching fresh data' );
-
-   const cacheStorage = await caches.open( cacheName );
-   await cacheStorage.add( url );
-   cachedData = await getCachedData( cacheName, url );
-   await deleteOldCaches( cacheName );
-
-   return cachedData;
-}
-
-// Get data from the cache.
-async function getCachedData( cacheName, url ) {
-   const cacheStorage   = await caches.open( cacheName );
-   const cachedResponse = await cacheStorage.match( url );
-
-   if ( ! cachedResponse || ! cachedResponse.ok ) {
-      return false;
-   }
-
-   return await cachedResponse.json();
-}
-
-// Delete any old caches to respect user's disk space.
-async function deleteOldCaches( currentCache ) {
-   const keys = await caches.keys();
-
-   for ( const key of keys ) {
-      const isOurCache = 'myapp-' === key.substr( 0, 6 );
-
-      if ( currentCache === key || ! isOurCache ) {
-         continue;
-      }
-
-      caches.delete( key );
-   }
-}
-
-try {
-   const data = await getData();
-   console.log( { data } );
-} catch ( error ) {
-   console.error( { error } );
-}
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers', '#cachestorage', 'CacheStorage')}}{{Spec2('Service Workers')}}Initial definition.
- -

Browser compatibility

- - - -

{{Compat("api.CacheStorage")}}

- -

See also

- - diff --git a/files/id/web/api/canvas_api/index.html b/files/id/web/api/canvas_api/index.html deleted file mode 100644 index 0cdd4219fe..0000000000 --- a/files/id/web/api/canvas_api/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Canvas API -slug: Web/API/Canvas_API -tags: - - API - - Canvas - - Gambar - - JavaScript - - Referensi -translation_of: Web/API/Canvas_API ---- -
{{CanvasSidebar}}
- -

Ditambahkan di HTML5, elemen HTML {{HTMLElement("canvas")}} dapat digunakan untuk menggambar grafik melalui skrip di JavaScript. Sebagai contoh, dapat digunakan untuk menggambar graf, membuat komposisi foto, mencipta animasi, atau bahkan melakukan pemrosesan atau rendering video secara waktu-nyata .

- -

Aplikasi Mozilla mendapat dukungan untuk <canvas> sejak Gecko 1.8 (i.e. Firefox 1.5). Elemen tersebut semula dikenalkan oleh Apple untuk Dashboard OS X dan Safari. Internet Explorer mendukung <canvas> sejak versi 9 dan seterusnya; untuk versi awal IE, sebuah halaman dapat secara efektif mendukung <canvas> dengan memasukkan skrip dari proyek Explorer Canvas Google. Google Chrome dan Opera 9 juga mendukung <canvas>.

- -

Elemen <canvas> juga digunakan oleh WebGL untuk menggambar grafik hardware-accelerated 3D di halaman web.

- -

Contoh

- -

Ini hanya cuplikan kode sederhana yang menggunakan metode  {{domxref("CanvasRenderingContext2D.fillRect()")}}.

- -

HTML

- -
<canvas id="canvas"></canvas>
-
- -

JavaScript

- -
var canvas = document.getElementById('canvas');
-var ctx = canvas.getContext('2d');
-
-ctx.fillStyle = 'green';
-ctx.fillRect(10, 10, 100, 100);
-
- -

Edit kode di bawah dan lihat perbaruan perubahannya di kanvas secara waktu-nyata:

- - - -

{{ EmbedLiveSample('Playable_code', 700, 360) }}

- -

Reference

- -
- -
- -

The interfaces related to the WebGLRenderingContext are referenced under WebGL.

- -

{{domxref("CanvasCaptureMediaStream")}} is related.

- -

Petunjuk dan tutorial

- -
-
Tutorial canvas
-
Tutorial komprehensif mengcakup penggunaan sederhana  <canvas> dan fitur lanjutannya.
-
Cuplikan kode: Canvas
-
Beberapa cuplikan kode pengembang berorientasi ekstensi yang melibatkan <canvas>.
-
Demo: ray-caster sederhana
-
Demo animasi ray-tracing menggunakan canvas.
-
Menggambar DOM objects ke canvas
-
Bagaimana menggambar konten DOM, seperti elemen HTML, pada canvas.
-
Memanipulasi video dengan canvas
-
Menggabungkan {{HTMLElement("video")}} dan {{HTMLElement("canvas")}} untuk memanipulasi data video secara real time.
-
- -

Sumber

- -

Generik

- - - -

Librari

- - - -

Spesifikasi

- - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}{{Spec2('HTML WHATWG')}}
- -

Lihat juga

- - diff --git a/files/id/web/api/console/index.html b/files/id/web/api/console/index.html deleted file mode 100644 index 05cdba529b..0000000000 --- a/files/id/web/api/console/index.html +++ /dev/null @@ -1,278 +0,0 @@ ---- -title: Console -slug: Web/API/Console -tags: - - API - - Debugging - - Interface - - NeedsCompatTable - - NeedsTranslation - - Reference - - TopicStub - - console - - web console -translation_of: Web/API/Console ---- -
{{APIRef("Console API")}}
- -

The Console object provides access to the browser's debugging console (e.g., the Web Console in Firefox). The specifics of how it works vary from browser to browser, but there is a de facto set of features that are typically provided.

- -

The Console object can be accessed from any global object, {{domxref("Window")}} on browsing scopes, {{domxref("WorkerGlobalScope")}}, and its specific variants in workers via property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as simply console. For example:

- -
console.log("Failed to open the specified link")
- -

This page documents the {{anch("Methods")}} available on the Console object and gives a few {{anch("Usage")}} examples.

- -

{{AvailableInWorkers}}

- -

Methods

- -
-
{{domxref("Console.assert()")}}
-
Log a message and stack trace to console if first argument is false.
-
{{domxref("Console.clear()")}}
-
Clear the console.
-
{{domxref("Console.count()")}}
-
Log the number of times this line has been called with the given label.
-
{{domxref("Console.debug()")}}
-
An alias for log() - starting with Chromium 58 this method is a no-op on Chromium browsers.
-
{{domxref("Console.dir()")}} {{Non-standard_inline}}
-
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
-
{{domxref("Console.dirxml()")}} {{Non-standard_inline}}
-
-

Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not.

-
-
{{domxref("Console.error()")}}
-
Outputs an error message. You may use string substitution and additional arguments with this method.
-
{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
-
An alias for error()
-
{{domxref("Console.group()")}}
-
Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
-
{{domxref("Console.groupCollapsed()")}}
-
Creates a new inline group, indenting all following output by another level; unlike group(), this starts with the inline group collapsed, requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd().
-
{{domxref("Console.groupEnd()")}}
-
Exits the current inline group.
-
{{domxref("Console.info()")}}
-
Informative logging information. You may use string substitution and additional arguments with this method.
-
{{domxref("Console.log()")}}
-
For general output of logging information. You may use string substitution and additional arguments with this method.
-
{{domxref("Console.profile()")}} {{Non-standard_inline}}
-
Starts the browser's build-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
-
{{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
-
Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
-
{{domxref("Console.table()")}}
-
Displays tabular data as a table.
-
{{domxref("Console.time()")}}
-
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
-
{{domxref("Console.timeEnd()")}}
-
Stops the specified timer and logs the elapsed time in seconds since its start.
-
{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
-
Adds a marker to the browser's Timeline or Waterfall tool.
-
{{domxref("Console.trace()")}}
-
Outputs a stack trace.
-
{{domxref("Console.warn()")}}
-
Outputs a warning message. You may use string substitution and additional arguments with this method.
-
- - -

Usage

- -

Outputting text to the console

- -

The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, and {{domxref("console.error()")}} methods. Each of these results in output that's styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.

- -

There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of the objects with which to replace them.

- -

Outputting a single object

- -

The simplest way to use the logging methods is to output a single object:

- -
var someObject = { str: "Some text", id: 5 };
-console.log(someObject);
-
- -

The output looks something like this:

- -
[09:27:13.475] ({str:"Some text", id:5})
- -

Outputting multiple objects

- -

You can also output multiple objects by simply listing them when calling the logging method, like this:

- -
var car = "Dodge Charger";
-var someObject = {str:"Some text", id:5};
-console.info("My first car was a", car, ". The object is: ", someObject);
- -

This output will look like this:

- -
[09:28:22.711] My first car was a Dodge Charger . The object is:  ({str:"Some text", id:5})
-
- -

Using string substitutions

- -

Gecko 9.0 {{geckoRelease("9.0")}} introduced support for string substitutions. When passing a string to one of the console object's methods that accepts a string, you may use these substitution strings:

- - - - - - - - - - - - - - - - - - - - - - - - -
Substitution stringDescription
%o or %OOutputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d or %iOutputs an integer. Number formatting is supported, for example  console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%sOutputs a string.
%fOutputs a floating-point value. Formatting is supported, for example  console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10
- -

Each of these pulls the next argument after the format string off the parameter list. For example:

- -
for (var i=0; i<5; i++) {
-  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
-}
-
- -

The output looks like this:

- -
[13:14:13.481] Hello, Bob. You've called me 1 times.
-[13:14:13.483] Hello, Bob. You've called me 2 times.
-[13:14:13.485] Hello, Bob. You've called me 3 times.
-[13:14:13.487] Hello, Bob. You've called me 4 times.
-[13:14:13.488] Hello, Bob. You've called me 5 times.
-
- -

Styling console output

- -

You can use the "%c" directive to apply a CSS style to console output:

- -
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
- -
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
- -
 
- -
- -
 
- -
-

Note: Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.

-
- -
 
- -
{{h3_gecko_minversion("Using groups in the console", "9.0")}}
- -

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

- -
Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.
- -

To exit the current group, simply call console.groupEnd(). For example, given this code:

- -
console.log("This is the outer level");
-console.group();
-console.log("Level 2");
-console.group();
-console.log("Level 3");
-console.warn("More of level 3");
-console.groupEnd();
-console.log("Back to level 2");
-console.groupEnd();
-console.debug("Back to the outer level");
-
- -

The output looks like this:

- -

nesting.png

- -
{{h3_gecko_minversion("Timers", "10.0")}}
- -

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

- -

For example, given this code:

- -
console.time("answer time");
-alert("Click to continue");
-console.timeEnd("answer time");
-
- -

will log the time needed by the user to discard the alert box:

- -

timerresult.png

- -

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

- -
Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
- -

Stack traces

- -

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:

- -
function foo() {
-  function bar() {
-    console.trace();
-  }
-  bar();
-}
-
-foo();
-
- -

The output in the console looks something like this:

- -

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
- -

Notes

- - - -

See also

- - - -

Other implementations

- - diff --git a/files/id/web/api/document/createelement/index.html b/files/id/web/api/document/createelement/index.html deleted file mode 100644 index 0f14c4e8ce..0000000000 --- a/files/id/web/api/document/createelement/index.html +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Document.createElement() -slug: Web/API/Document/createElement -tags: - - API - - DOM - - Document - - Metode - - Referensi - - createElement -translation_of: Web/API/Document/createElement ---- -
{{APIRef("DOM")}}
- -

Dalam sebuah dokumen HTML, metode document.createElement() membuat elemen HTML yang ditentukan oleh tagName, atau sebuah  {{domxref("HTMLUnknownElement")}} jika tagName tidak dikenali.

- -
-

Catatan: Dalam sebuah dokumen XUL , ini membuat elemen XUL yang ditentukan. Pada dokumen lain, ini membuat sebuah elemen dengan sebuah namespace URI yang null.

-
- -

Sintaks

- -
var element = document.createElement(tagName[, options]);
-
- -

Parameter

- -
-
tagName
-
Sebuah string yang menentukan tipe dari elemen yang akan dibuat. {{domxref("Node.nodeName", "nodeName")}} dari elemen dibuat dengan nilai tagName. Jangan menggunakan nama yang memenuhi syarat (seperti "html:a") dengan metode ini. Ketika dipanggil pada sebuah dokumen HTML, createElement() mengubah tagName menjadi lower case sebelum membuat elemen. Pada Firefox, Opera, dan Chrome, createElement(null) bekerja seperti createElement("null").
-
options{{optional_inline}}
-
Sebuah objek opsional ElementCreationOptions berisi sebuah properti tunggal bernama is, yang nilainya adalah nama tag untuk sebuah elemen khusus yang sebelumnya didefinisikan menggunakan customElements.define(). Lihat {{anch("Web component example")}} untuk lebih jelasnya.
-
- -

Return value

- -

Element baru.

- -

Contoh

- -

Contoh dasar

- -

Ini membuat sebuah <div> baru dan memasukannya sebelum elemen dengan ID "div1".

- -

HTML

- -
<!DOCTYPE html>
-<html>
-<head>
-  <title>||Bekerja dengan elemen||</title>
-</head>
-<body>
-  <div id="div1">Teks di atas telah dibuat secara dinamis.</div>
-</body>
-</html>
-
- -

JavaScript

- -
document.body.onload = addElement;
-
-function addElement () {
-  // membuat sebuah elemen div baru
-  var newDiv = document.createElement("div");
-  // dan memberikannya sebuah konten
-  var newContent = document.createTextNode("Hi there and greetings!");
-  // menambahkan teks terebut ke div yang baru dibuat
-  newDiv.appendChild(newContent);
-
-  // menambah elemen yang baru dibuat berserta isinya ke dalam DOM
-  var currentDiv = document.getElementById("div1");
-  document.body.insertBefore(newDiv, currentDiv);
-}
- -

{{EmbedLiveSample("Basic_example", 500, 50)}}

- -

Contoh komponen web

- -

Contoh cuplikan berikut diambil dari contoh dari expanding-list-web-component kami (lihat juga secara langsung). Dalam kasus ini, elemen khusus kami memperluas {{domxref("HTMLUListElement")}}, yang mewakili elemen {{htmlelement("ul")}}.

- -
// Membuat sebuah kelas untuk elemen
-class ExpandingList extends HTMLUListElement {
-  constructor() {
-    // Selalu memanggil super dulu di konstruktor
-    super();
-
-    // definisi konstruktor dihilangkan untuk singkatnya
-    ...
-  }
-}
-
-// Mendefinisi elemen baru
-customElements.define('expanding-list', ExpandingList, { extends: "ul" });
- -

Jika kita ingin untuk membuat sebuah instance dari elemen ini secara terprogram, kita akan menggunakan sebuah panggilan di sepanjang baris berikut:

- -
let expandingList = document.createElement('ul', { is : 'expanding-list' })
- -

Elemen baru akan diberikan sebuah atribut is yang nilainya adalah nama tag elemen khusus.

- -
-

Catatan: Untuk kompabilitas ke belakang untuk versi sebelumnya dari Spesifikasi Elemen khusus, beberapa peramban (browser) akan memungkinkan Anda untuk melewatkan sebuah string di sini bukan pada sebuah objek, yang mana nilai string  adalah nama tag elemen khusus.

-
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}{{Spec2('DOM WHATWG')}} 
- -

Kompabilitas peramban

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1][2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
argumen options{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatGeckoDesktop(50)}}[4][5]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
argumen options{{CompatVersionUnknown}}{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[3]
-
- -

[1] Dimulai dengan Gecko 22.0 {{geckoRelease("22.0")}} createElement() tidak lagi menggunakan antarmuka {{domxref("HTMLSpanElement")}} ketika argumennya adalah "bgsounds", "multicol", atau "image".  Sebagai gantinya, HTMLUnknownElement digunakan untuk "bgsound" dan "multicol" dan {{domxref("HTMLElement")}} HTMLElement digunakan untuk "image".

- -

[2] Implementasi Gecko dari createElement tidak sesuai dengan spesifikasi DOM untuk dokumen XUL dan XHTML: localName dan namespaceURI tidak diatur ke null pada elemen yang dibuat. Lihat {{ Bug(280692) }} untuk lebih jelasnya.

- -

[3] Pada versi sebelumnya dari spesifikasi, argumen ini hanyalah sebuah string yang nilainyaadalah nama tag elemen khusus. Misalnya bisa saja document.createElement("button", "custom-button") daripada document.createElement("button", {is: "custom-button"}). Demi kompabilitas ke belakang, Chrome menerima kedua bentuk tersebut, meskipun bentuk string sudah usang.

- -

[4] Liat [3] di atas: seperti Chrome, Firefox menerima string, bukan sebuah objek di sini, tetapi hanya dari versi 51 dan seterusnya. Pada versi 50, options harus sebuah objek.

- -

[5] Untuk eksperimen dengan elemen khusus di Firefox, Anda harus mengatur preferensi dom.webcomponents.enabled dan dom.webcomponents.customelements.enabled menjadi true.

- -

Catatan Quantum CSS

- - - -

Lihat juga

- - diff --git a/files/id/web/api/document/index.html b/files/id/web/api/document/index.html deleted file mode 100644 index a058175001..0000000000 --- a/files/id/web/api/document/index.html +++ /dev/null @@ -1,576 +0,0 @@ ---- -title: Document -slug: Web/API/Document -tags: - - API - - DOM - - Interface - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/API/Document ---- -
{{APIRef}}
- -
 
- -

The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. The DOM tree includes elements such as {{HTMLElement("body")}} and {{HTMLElement("table")}}, among many others. It provides functionality which is global to the document, such as obtaining the page's URL and creating new elements in the document.

- -

{{inheritanceDiagram}}

- -

The Document interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. HTML, XML, SVG, …), a larger API is available: HTML documents, served with the text/html content type, also implement the {{domxref("HTMLDocument")}} interface, wherease SVG documents implement the {{domxref("SVGDocument")}} interface.

- -

Properties

- -

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

- -
-
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
-
Provides access to all elements with an id. This is a legacy, non-standard interface and you should use the {{domxref("document.getElementById()")}} method instead.
-
{{domxref("Document.async")}} {{Deprecated_inline}}
-
Used with {{domxref("Document.load")}} to indicate an asynchronous request.
-
{{domxref("Document.characterSet")}} {{readonlyinline}}
-
Returns the character set being used by the document.
-
{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
-
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
-
{{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}
-
Indicates whether the document is rendered in quirks or strict mode.
-
{{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}
-
Returns the Content-Type from the MIME Header of the current document.
-
{{domxref("Document.doctype")}} {{readonlyinline}}
-
Returns the Document Type Definition (DTD) of the current document.
-
{{domxref("Document.documentElement")}} {{readonlyinline}}
-
Returns the {{domxref("Element")}} that is a direct child of the document. For HTML documents, this is normally the HTML element.
-
{{domxref("Document.documentURI")}} {{readonlyinline}}
-
Returns the document location as a string.
-
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
-
Should return a {{domxref("DOMConfiguration")}} object.
-
{{domxref("Document.fullscreen")}} {{obsolete_inline}}
-
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
-
{{domxref("Document.hidden")}} {{readonlyinline}}
-
-
{{domxref("Document.implementation")}} {{readonlyinline}}
-
Returns the DOM implementation associated with the current document.
-
{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
-
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
-
{{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}
-
Returns the name of the style sheet set that was last enabled. Has the value null until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
-
{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}
-
Returns a {{jsxref("Boolean")}} that is true only if this document is synthetic, such as a standalone image, video, audio file, or the like.
-
{{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
-
The element that's currently in full screen mode for this document.
-
{{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
-
true if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.
-
{{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
-
Returns the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.
-
{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
-
Returns the preferred style sheet set as specified by the page author.
-
{{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}
-
Returns a reference to the {{domxref("Element")}} that scrolls the document.
-
{{domxref("Document.selectedStyleSheetSet")}}
-
Returns which style sheet set is currently in use.
-
{{domxref("Document.styleSheets")}} {{readonlyinline}}
-
Returns a list of the style sheet objects on the current document.
-
{{domxref("Document.styleSheetSets")}} {{readonlyinline}}
-
Returns a list of the style sheet sets available on the document.
-
{{domxref("Document.timeline")}} {{readonlyinline}}
-
-
{{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}
-
-
{{domxref("Document.URL")}} {{readonlyinline}}
-
Returns ...
-
{{domxref("Document.visibilityState")}} {{readonlyinline}}
-
-
{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
-
Returns the encoding as determined by the XML declaration.
-
{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}
-
Returns true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false.
-
{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}
-
Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent.
-
- -

The Document interface is extended with the {{domxref("ParentNode")}} interface:

- -

{{page("/en-US/docs/Web/API/ParentNode","Properties")}}

- -

Extension for HTML document

- -

The Document interface for HTML documents inherits from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents.

- -
-
{{domxref("Document.activeElement")}} {{readonlyinline}}
-
Returns the currently focused element.
-
{{domxref("Document.alinkColor")}} {{Deprecated_inline}}
-
Returns or sets the color of active links in the document body.
-
{{domxref("Document.anchors")}}
-
Returns a list of all of the anchors in the document.
-
{{domxref("Document.applets")}} {{Deprecated_inline}}
-
Returns an ordered list of the applets within a document.
-
{{domxref("Document.bgColor")}} {{Deprecated_inline}}
-
Gets/sets the background color of the current document.
-
{{domxref("Document.body")}}
-
Returns the {{HTMLElement("body")}} element of the current document.
-
{{domxref("Document.cookie")}}
-
Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
-
{{domxref("Document.defaultView")}} {{readonlyinline}}
-
Returns a reference to the window object.
-
{{domxref("Document.designMode")}}
-
Gets/sets the ability to edit the whole document.
-
{{domxref("Document.dir")}} {{readonlyinline}}
-
Gets/sets directionality (rtl/ltr) of the document.
-
{{domxref("Document.domain")}} {{readonlyinline}}
-
Returns the domain of the current document.
-
{{domxref("Document.embeds")}} {{readonlyinline}}
-
Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
-
{{domxref("document.fgColor")}} {{Deprecated_inline}}
-
Gets/sets the foreground color, or text color, of the current document.
-
{{domxref("Document.forms")}} {{readonlyinline}}
-
Returns a list of the {{HTMLElement("form")}} elements within the current document.
-
{{domxref("Document.head")}} {{readonlyinline}}
-
Returns the {{HTMLElement("head")}} element of the current document.
-
{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}
-
Gets/sets the height of the current document.
-
{{domxref("Document.images")}} {{readonlyinline}}
-
Returns a list of the images in the current document.
-
{{domxref("Document.lastModified")}} {{readonlyinline}}
-
Returns the date on which the document was last modified.
-
{{domxref("Document.linkColor")}} {{Deprecated_inline}}
-
Gets/sets the color of hyperlinks in the document.
-
{{domxref("Document.links")}} {{readonlyinline}}
-
Returns a list of all the hyperlinks in the document.
-
{{domxref("Document.location")}} {{readonlyinline}}
-
Returns the URI of the current document.
-
{{domxref("Document.plugins")}} {{readonlyinline}}
-
Returns a list of the available plugins.
-
{{domxref("Document.readyState")}} {{readonlyinline}}  {{gecko_minversion_inline("1.9.2")}}
-
Returns loading status of the document.
-
{{domxref("Document.referrer")}} {{readonlyinline}}
-
Returns the URI of the page that linked to this page.
-
{{domxref("Document.scripts")}} {{readonlyinline}}
-
Returns all the {{HTMLElement("script")}} elements on the document.
-
{{domxref("Document.title")}}
-
Sets or gets title of the current document.
-
{{domxref("Document.URL")}} {{readonlyInline}}
-
Returns the document location as a string.
-
{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
-
Gets/sets the color of visited hyperlinks.
-
{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}
-
Returns the width of the current document.
-
- -

Event handlers

- -
-
{{domxref("GlobalEventHandlers.onabort")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("abort")}} event is raised.
-
{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("afterscriptexecute")}} event.
-
{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("beforescriptexecute")}} event.
-
{{domxref("GlobalEventHandlers.onblur")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("blur")}} event is raised.
-
{{domxref("GlobalEventHandlers.oncancel")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cancel")}} event is raised.
-
{{domxref("GlobalEventHandlers.oncanplay")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplay")}} event is raised.
-
{{domxref("GlobalEventHandlers.oncanplaythrough")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.
-
{{domxref("GlobalEventHandlers.onchange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("change")}} event is raised.
-
{{domxref("GlobalEventHandlers.onclick")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("click")}} event is raised.
-
{{domxref("GlobalEventHandlers.onclose")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("close")}} event is raised.
-
{{domxref("GlobalEventHandlers.oncontextmenu")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.
-
{{domxref("Document.oncopy")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("copy")}} event.
-
{{domxref("GlobalEventHandlers.oncuechange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cuechange")}} event is raised.
-
{{domxref("Document.oncut")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("cut")}} event.
-
{{domxref("GlobalEventHandlers.ondblclick")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dblclick")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondrag")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drag")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondragend")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragend")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondragenter")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragenter")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondragexit")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragexit")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondragleave")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragleave")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondragover")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragover")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondragstart")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragstart")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondrop")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drop")}} event is raised.
-
{{domxref("GlobalEventHandlers.ondurationchange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("durationchange")}} event is raised.
-
{{domxref("GlobalEventHandlers.onemptied")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("emptied")}} event is raised.
-
{{domxref("GlobalEventHandlers.onended")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ended")}} event is raised.
-
{{domxref("GlobalEventHandlers.onerror")}}
-
Is an {{domxref("OnErrorEventHandler")}} representing the code to be called when the {{event("error")}} event is raised.
-
{{domxref("GlobalEventHandlers.onfocus")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("focus")}} event is raised.
-
{{domxref("Document.onfullscreenchange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
-
{{domxref("Document.onfullscreenerror")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
-
{{domxref("GlobalEventHandlers.oninput")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("input")}} event is raised.
-
{{domxref("GlobalEventHandlers.oninvalid")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("invalid")}} event is raised.
-
{{domxref("GlobalEventHandlers.onkeydown")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keydown")}} event is raised.
-
{{domxref("GlobalEventHandlers.onkeypress")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keypress")}} event is raised.
-
{{domxref("GlobalEventHandlers.onkeyup")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keyup")}} event is raised.
-
{{domxref("GlobalEventHandlers.onload")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("load")}} event is raised.
-
{{domxref("GlobalEventHandlers.onloadeddata")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.
-
{{domxref("GlobalEventHandlers.onloadedmetadata")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.
-
{{domxref("GlobalEventHandlers.onloadstart")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadstart")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmousedown")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousedown")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmouseenter")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmouseleave")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmousemove")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousemove")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmouseout")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseout")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmouseover")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseover")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmouseup")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseup")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmousewheel")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpause")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pause")}} event is raised.
-
{{domxref("Document.onpaste")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("paste")}} event.
-
{{domxref("GlobalEventHandlers.onplay")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("play")}} event is raised.
-
{{domxref("GlobalEventHandlers.onplaying")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("playing")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointerdown")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerdown")}} event is raised.
-
{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}
-
Represents the event handling code for the {{event("pointerlockchange")}} event.
-
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
-
Represetnts the event handling code for the {{event("pointerlockerror")}} event.
-
{{domxref("GlobalEventHandlers.onpointermove")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointermove")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointerup")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerup")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointercancel")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointercancel")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointerover")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerover")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointerout")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerout")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointerenter")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerevent")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointerleave")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerleave")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockchange")}} event is raised.
-
{{domxref("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockerror")}} event is raised.
-
{{domxref("GlobalEventHandlers.onprogress")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("progress")}} event is raised.
-
{{domxref("GlobalEventHandlers.onratechange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ratechange")}} event is raised.
-
{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
-
Represents the event handling code for the {{event("readystatechange")}} event.
-
{{domxref("GlobalEventHandlers.onreset")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("reset")}} event is raised.
-
{{domxref("GlobalEventHandlers.onscroll")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("scroll")}} event is raised.
-
{{domxref("GlobalEventHandlers.onseeked")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeked")}} event is raised.
-
{{domxref("GlobalEventHandlers.onseeking")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeking")}} event is raised.
-
{{domxref("GlobalEventHandlers.onselect")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("select")}} event is raised.
-
{{domxref("GlobalEventHandlers.onselectstart")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectstart")}} event is raised.
-
{{domxref("Document.onselectionchange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
-
{{domxref("GlobalEventHandlers.onshow")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("show")}} event is raised.
-
{{domxref("GlobalEventHandlers.onsort")}} {{experimental_inline}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("sort")}} event is raised.
-
{{domxref("GlobalEventHandlers.onstalled")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("stalled")}} event is raised.
-
{{domxref("GlobalEventHandlers.onsubmit")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("submit")}} event is raised.
-
{{domxref("GlobalEventHandlers.onsuspend")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("suspend")}} event is raised.
-
{{domxref("GlobalEventHandlers.ontimeupdate")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("timeupdate")}} event is raised.
-
{{domxref("GlobalEventHandlers.onvolumechange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("volumechange")}} event is raised.
-
{{domxref("GlobalEventHandlers.onwaiting")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("waiting")}} event is raised.
-
{{domxref("Document.onwheel")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("wheel")}} event.
-
- -

Methods

- -

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

- -
-
{{domxref("Document.adoptNode()")}}
-
Adopt node from an external document.
-
{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
-
See {{domxref("Window.captureEvents")}}.
-
{{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}
-
Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.
-
{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
-
Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.
-
{{domxref("Document.createAttribute()")}}
-
Creates a new {{domxref("Attr")}} object and returns it.
-
{{domxref("Document.createAttributeNS()")}}
-
Creates a new attribute node in a given namespace and returns it.
-
{{domxref("Document.createCDATASection()")}}
-
Creates a new CDATA node and returns it.
-
{{domxref("Document.createComment()")}}
-
Creates a new comment node and returns it.
-
{{domxref("Document.createDocumentFragment()")}}
-
Creates a new document fragment.
-
{{domxref("Document.createElement()")}}
-
Creates a new element with the given tag name.
-
{{domxref("Document.createElementNS()")}}
-
Creates a new element with the given tag name and namespace URI.
-
{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}
-
Creates a new entity reference object and returns it.
-
{{domxref("Document.createEvent()")}}
-
Creates an event object.
-
{{domxref("Document.createNodeIterator()")}}
-
Creates a {{domxref("NodeIterator")}} object.
-
{{domxref("Document.createProcessingInstruction()")}}
-
Creates a new {{domxref("ProcessingInstruction")}} object.
-
{{domxref("Document.createRange()")}}
-
Creates a {{domxref("Range")}} object.
-
{{domxref("Document.createTextNode()")}}
-
Creates a text node.
-
{{domxref("Document.createTouch()")}}
-
Creates a {{domxref("Touch")}} object.
-
{{domxref("Document.createTouchList()")}}
-
Creates a {{domxref("TouchList")}} object.
-
{{domxref("Document.createTreeWalker()")}}
-
Creates a {{domxref("TreeWalker")}} object.
-
{{domxref("Document.elementFromPoint()")}}{{experimental_inline}}
-
Returns the topmost element at the specified coordinates. 
-
{{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}
-
Returns an array of all elements at the specified coordinates.
-
{{domxref("Document.enableStyleSheetsForSet()")}}
-
Enables the style sheets for the specified style sheet set.
-
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
-
Release the pointer lock.
-
{{domxref("Document.getAnimations()")}} {{experimental_inline}}
-
Returns an array of all {{domxref("Animation")}} objects currently in effect whose target elements are descendants of the document.
-
{{domxref("Document.getElementsByClassName()")}}
-
Returns a list of elements with the given class name.
-
{{domxref("Document.getElementsByTagName()")}}
-
Returns a list of elements with the given tag name.
-
{{domxref("Document.getElementsByTagNameNS()")}}
-
Returns a list of elements with the given tag name and namespace.
-
{{domxref("Document.importNode()")}}
-
Returns a clone of a node from an external document.
-
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
-
Replaces entities, normalizes text nodes, etc.
-
{{domxref("Document.registerElement()")}} {{experimental_inline}}
-
Registers a web component.
-
{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
-
Releases the current mouse capture if it's on an element in this document.
-
{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
-
See {{domxref("Window.releaseEvents()")}}.
-
{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}
-
See {{domxref("Window.routeEvent()")}}.
-
{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
-
Allows you to change the element being used as the background image for a specified element ID.
-
- -

The Document interface is extended with the {{domxref("ParentNode")}} interface:

- -
-
{{domxref("document.getElementById","document.getElementById(String id)")}}
-
Returns an object reference to the identified element.
-
{{domxref("document.querySelector","document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
-
Returns the first Element node within the document, in document order, that matches the specified selectors.
-
{{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
-
Returns a list of all the Element nodes within the document that match the specified selectors.
-
- -

The Document interface is extended with the {{domxref("XPathEvaluator")}} interface:

- -
-
{{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}
-
Compiles an XPathExpression which can then be used for (repeated) evaluations.
-
{{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}
-
Creates an {{domxref("XPathNSResolver")}} object.
-
{{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
-
Evaluates an XPath expression.
-
- -

Extension for HTML documents

- -

The Document interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents:

- -
-
{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
-
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
-
{{domxref("document.close()")}}
-
Closes a document stream for writing.
-
{{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}
-
On an editable document, executes a formating command.
-
{{domxref("document.getElementsByName","document.getElementsByName(String name)")}}
-
Returns a list of elements with the given name.
-
{{domxref("document.getSelection()")}}
-
Returns a {{domxref("Selection")}} object related to text selected in the document.
-
{{domxref("document.hasFocus()")}}
-
Returns true if the focus is currently located anywhere inside the specified document.
-
{{domxref("document.open()")}}
-
Opens a document stream for writing.
-
{{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}
-
Returns true if the formating command can be executed on the current range.
-
{{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}
-
Returns true if the formating command is in an indeterminate state on the current range.
-
{{domxref("document.queryCommandState","document.queryCommandState(String command)")}}
-
Returns true if the formating command has been executed on the current range.
-
{{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}
-
Returns true if the formating command is supported on the current range.
-
{{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}
-
Returns the current value of the current range for a formating command.
-
{{domxref("document.write","document.write(String text)")}}
-
Writes text in a document.
-
{{domxref("document.writeln","document.writeln(String text)")}}
-
Writes a line of text in a document.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Selection API', '', 'Extend Document and GlobalEventHandlers')}}{{Spec2('Selection API')}}Adds onselectstart and onselectionchange.
{{SpecName('DOM1','#i-Document','Document')}}{{Spec2('DOM1')}}Initial definition for the interface
{{SpecName('DOM2 Core','#i-Document','Document')}}{{Spec2('DOM2 Core')}}Supersede DOM 1
{{SpecName('DOM3 Core','#i-Document','Document')}}{{Spec2('DOM3 Core')}}Supersede DOM 2
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Intend to supersede DOM 3
{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}{{Spec2('HTML WHATWG')}}Turn the {{domxref("HTMLDocument")}} interface into a Document extension.
{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}{{Spec2('DOM3 XPath')}}Define the {{domxref("XPathEvaluator")}} interface which extend document.
{{SpecName('HTML Editing','#dom-document-getselection','Document')}}{{Spec2('HTML Editing')}}Extend the Document interface
{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM View')}}Extend the Document interface
{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM')}}Extend the Document interface
{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}{{Spec2('Pointer Lock')}}Extend the Document interface
- -

Browser compatibility notes

- -

Firefox notes

- -

Mozilla defines a set of non-standard properties made only for XUL content:

- -
-
{{domxref("document.currentScript")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
-
Returns the {{HTMLElement("script")}} element that is currently executing.
-
{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}
-
(Mozilla add-ons only!) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
-
{{domxref("document.popupNode")}}
-
Returns the node upon which a popup was invoked.
-
{{domxref("document.tooltipNode")}}
-
Returns the node which is the target of the current tooltip.
-
- -

Mozilla also define some non-standard methods:

- -
-
{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}
-
This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
-
{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}
-
Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
-
{{domxref("document.loadOverlay")}}
-
Loads a XUL overlay dynamically. This only works in XUL documents.
-
{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}
-
This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
-
- -

Internet Explorer notes

- -

Microsoft defines some non-standard properties:

- -
-
{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}
-
Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN.
-
Internet Explorer does not support all methods from the Node interface in the Document interface:
-
- -
-
{{domxref("document.contains")}}
-
As a work-around, document.body.contains() can be used.
-
- -

 

diff --git a/files/id/web/api/document/links/index.html b/files/id/web/api/document/links/index.html deleted file mode 100644 index 4a2d6a5a1b..0000000000 --- a/files/id/web/api/document/links/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Document.links -slug: Web/API/Document/links -tags: - - API - - Document - - Property - - Reference -translation_of: Web/API/Document/links ---- -

{{ APIRef("DOM") }}

- -

Properti links mengembalikan sebuah collection dari semua elemen {{HTMLElement("area")}} dan elemen {{HTMLElement("a")}} pada sebuah dokumen dengan sebuah nilai pada atribut href .

- -

Sintaks

- -
nodeList = document.links
-
- -

Contoh

- -
var links = document.links;
-for(var i = 0; i < links.length; i++) {
-  var linkHref = document.createTextNode(links[i].href);
-  var lineBreak = document.createElement("br");
-  document.body.appendChild(linkHref);
-  document.body.appendChild(lineBreak);
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('HTML WHATWG', '#dom-document-links', 'Document.links')}}{{ Spec2('HTML WHATWG') }} 
{{SpecName("DOM2 HTML", "html.html#ID-7068919", "document.links")}}{{Spec2("DOM2 HTML")}}Initial definition
- -

Kompabilitas browser

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
diff --git a/files/id/web/api/document/write/index.html b/files/id/web/api/document/write/index.html deleted file mode 100644 index ac3912c415..0000000000 --- a/files/id/web/api/document/write/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Document.write() -slug: Web/API/Document/write -tags: - - API - - DOM - - Method - - Reference -translation_of: Web/API/Document/write ---- -
{{ ApiRef("DOM") }}
- -

Menuliskan teks string ke sebuah dokumen stream yang dibuka dengan document.open().

- -
Catatan: ketika document.write menulis ke dokumen stream, memanggil document.write pada sebuah dokumen tertutup (termuat), dokumen secara otomatis memanggil document.open, yang akan menghapus dokumen.
- -

Sintaks

- -
document.write(markup);
-
- -

markup merupakan sebuah string yang berisi teks untuk ditulis ke dalam dokumen.

- -

Contoh

- -
<html>
-
-<head>
-<title>write example</title>
-
-<script>
-
-function newContent()
-{
-alert("load new content");
-document.open();
-document.write("<h1>Out with the old - in with the new!</h1>");
-document.close();
-}
-
-</script>
-</head>
-
-<body onload="newContent();">
-<p>Some original document content.</p>
-</body>
-</html>
-
- -

Catatan

- -

Menulis ke sebuah dokumen yang telah dimuat tanpa memanggil document.open() akan secara otomatis melakukan panggilan document.open. Setelah selesai menulis, disarankan untuk memanggil document.close(), untuk meminta browser untuk menyelesaikan memuat halaman. Teks yang anda tulis akan di parse ke dalam stuktur model dokumen tersebut. Pada contoh diatas, elemen h1 menjadi sebuah node pada document.

- -

Jika pemanggilan document.write() merpakan embeded pada inline tag html <script> tag, maka tidak akan memanggil document.open(). Sebagai contoh:

- -
<script>
-  document.write("<h1>Main title</h1>")
-</script>
-
- -
Catatan: document.write an document.writeln tidak berfungsi di dokumen XHTML ( anda akan mendapat peringatan "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] error pada konsole). Ini terjadi ketika membuka sebuah file lokal dengan ekstensi file .xhtml atau dokumen lain yang disajikan dengan MIME type application/xhtml+xml . Informasi lengkap tersedia di W3C XHTML FAQ.
- -
Catatan: document.write pada script deferred atau asynchronous akan diabaikan, dan anda mendapatkan peringatan error "A call to document.write() from an asynchronously-loaded external script was ignored" pada konsole.
- -

Spesifikasi

- - - -

Lihat juga

- - diff --git a/files/id/web/api/element/error_event/index.html b/files/id/web/api/element/error_event/index.html deleted file mode 100644 index 242bbba9c3..0000000000 --- a/files/id/web/api/element/error_event/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: error -slug: Web/API/Element/error_event -translation_of: Web/API/Element/error_event -original_slug: Web/Events/error ---- -

Event error ditampilkan ketika sumberdaya gagal dimuat.

- -

Informasi umum

- -
-
Spesifikasi
-
DOM L3
-
Antar muka
-
UIEvent jika digenerasikan dari antarmuka pengguna, event sebaliknya.
-
Bubbles
-
No
-
Cancelable
-
No
-
Target
-
Element
-
Default Action
-
None
-
- -

Properti

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
- -

Lihat Juga

- -

{{domxref("GlobalEventHandlers.onerror")}} - window.onerror dan element.onerror.

diff --git a/files/id/web/api/event/currenttarget/index.html b/files/id/web/api/event/currenttarget/index.html deleted file mode 100644 index f44c5d54a9..0000000000 --- a/files/id/web/api/event/currenttarget/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Event.currentTarget -slug: Web/API/Event/currentTarget -tags: - - API - - DOM - - Gecko - - events -translation_of: Web/API/Event/currentTarget ---- -

{{APIRef("DOM")}}

- -

Mengidentifikasi event untuk target saat ini, seperti ketika event melalui DOM. Event tersebut selalu mengacu kepada lemen yang terikat dengan event handler, sebagai lawan dari event.target yang mana mengidentifikasi elemen ketika event tersebut terjadi.

- -

Contoh

- -

event.currentTarget sangat menarik untuk digunakan ketika menyatukan event handler yang sama ke beberapa element.

- -
function hide(e){
-  e.currentTarget.style.visibility = "hidden";
-  console.log(e.currentTarget);
-  // Ketika fungsi digunakan seperti event handler: this === e.currentTarget
-}
-
-var ps = document.getElementsByTagName('p');
-
-for(var i = 0; i < ps.length; i++){
-  // console: print the clicked <p> element
-  ps[i].addEventListener('click', hide, false);
-}
-// console: print <body>
-document.body.addEventListener('click', hide, false);
-
-// click dan paragraph akan menghilang
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName("DOM WHATWG", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM4")}} 
{{SpecName("DOM3 Events", "#dfn-current-event-target", "current event target")}}{{Spec2("DOM3 Events")}} 
{{SpecName("DOM2 Events", "#Events-Event-currentTarget", "Event.currentTarget")}}{{Spec2("DOM2 Events")}}Definisi awal
- -

Kesesuaian browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}10.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}10.0
-
- -

[1] Dalam Internet Explorer 6 sampai 8, event modelnya berbeda. Event listener(s) nya terikat dengan metode non-standard {{domxref("EventTarget.attachEvent")}}. Dalam model ini, tidak ada yang setara dengan event.currentTarget dan this adalah objek global. Satu solusin untuk meniru fitur event.currentTarget adalah dengan cara membungkus handler anda di dalam fungsi memanggil handler tersebut menggunakan Function.prototype.call dengan elemen sebagai argumen awal. Dengan cara ini, this akan menampilkan hasil yang diharapkan.

- -

Lihat juga

- -

Perbandingan dari Event Targets

diff --git a/files/id/web/api/event/index.html b/files/id/web/api/event/index.html deleted file mode 100644 index 952082247b..0000000000 --- a/files/id/web/api/event/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: Event -slug: Web/API/Event -tags: - - API - - DOM - - Event - - Interface - - Reference -translation_of: Web/API/Event ---- -

{{APIRef("DOM")}}

- -

Antarmuka Event mewakili setiap event pada DOM. mengandung properti umum dan method ke setiap event.

- -

Banyak sekali antarmuka lain yang menginplementasikan antarmuka Event, baik secara langsung atau dengan mengimplementsikan antarmuka lain dimana diantaranya:

- -
- -
- -

Konstruktor

- -
-
{{domxref("Event.Event", "Event()")}}
-
Membuat sebuah object Event
-
- -

Properti

- -

Antarmuka ini tidak mewarisi properti manapun.

- -
-
{{domxref("Event.bubbles")}} {{readonlyinline}}
-
Sebuah boolean yang menunjukan apakah event bubbles melalui DOM atau tidak.
-
{{domxref("Event.cancelBubble")}} {{non-standard_inline}}
-
Alternatif non-standar untuk {{domxref("Event.stopPropagation()")}}.
-
{{domxref("Event.cancelable")}} {{readonlyinline}}
-
Sebuah boolean yang menunjukan apakah event bisa dibatalkan.
-
{{domxref("Event.currentTarget")}} {{readonlyinline}}
-
Sebuah referensi untuk target terdaftar saat ini untuk event.
-
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
-
Menunjukan apakah {{domxref("event.preventDefault()")}} telah dipanggil pada event atau belum.
-
{{domxref("Event.eventPhase")}} {{readonlyinline}}
-
Menunjukan fase aliran event yang sedang diproses.
-
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
-
Eksplisit target dari event (Mozilla-specific).
-
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
-
Target dari event, sebelum penargetan ulang lain (Mozilla-specific).
-
{{domxref("Event.returnValue")}} {{non-standard_inline}}
-
Alternatif nonstandard untuk {{domxref("Event.preventDefault()")}} dan {{domxref("Event.defaultPrevented")}}. (spesifik Internet Explorer lama)
-
{{domxref("Event.srcElement")}} {{non-standard_inline}}
-
Alias nonstandard untuk {{domxref("Event.target")}}. (spesifik Internet Explorer lama)
-
{{domxref("Event.target")}} {{readonlyinline}}
-
Sebuah referensi untuk target dimana event pertama kali dikirimkan.
-
{{domxref("Event.timeStamp")}} {{readonlyinline}}
-
Waktu ketika event dibuat.
-
{{domxref("Event.type")}} {{readonlyinline}}
-
Nama dari event (case-insensitive).
-
{{domxref("Event.isTrusted")}} {{readonlyinline}}
-
Menunjukan apakah event di terima browser atau tidak (mis. ketika user klik) atau dengan sebuah script (menggunakan sebuah method event buatan, seperti event.initEvent)
-
- -

Method

- -

Antarmuka ini tidak mewarisi method manapun.

- -
-
{{domxref("Event.initEvent()")}} {{deprecated_inline}}
-
Menginisialisasi nilai dari Event yang dibuat. Jika event telah dikirimkan, method ini tidak akan digunakan.
-
{{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
-
Mencegah event agar tidak menggelegak. Usang, gunakan {{domxref("event.stopPropagation")}} sebagai gantinya.
-
{{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
-
Usang, gunakan {{domxref("event.stopPropagation")}} sebagai gantinya.
-
{{domxref("Event.preventDefault()")}}
-
Membatalkan event event (jika cancelable).
-
{{domxref("Event.stopImmediatePropagation()")}}
-
Khusus untuk event ini, tidak ada listener lain yang akan dipanggil. Baik yang ada pada elemen yang sama, maupunyang ada pada elemen yang akan di lalui nantinya (pada fase capture, misalnya)
-
{{domxref("Event.stopPropagation()")}}
-
Menghentikan penyebaran events lebih jauh pada DOM.
-
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
-
Non-standard. Mengembailkan nilai dari {{domxref("Event.defaultPrevented")}}. Gunakan {{domxref("Event.defaultPrevented")}} sebagai gantinya.
-
- -

Lihat Juga

- - diff --git a/files/id/web/api/event/target/index.html b/files/id/web/api/event/target/index.html deleted file mode 100644 index 52397c0827..0000000000 --- a/files/id/web/api/event/target/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Event.target -slug: Web/API/Event/target -translation_of: Web/API/Event/target ---- -
{{ApiRef("DOM")}}
- -

The target property of the {{domxref("Event")}} interface is a reference to the object onto which the event was dispatched. It is different from {{domxref("Event.currentTarget")}} when the event handler is called during the bubbling or capturing phase of the event.

- -

Syntax

- -
var theTarget = event.target;
- -

Value

- -

{{domxref("EventTarget")}}

- -

Example

- -

Properti event.target dapat digunakan untuk mengimplementasikan event delegation.

- -
// Membuat sebuah list
-var ul = document.createElement('ul');
-document.body.appendChild(ul);
-
-var li1 = document.createElement('li');
-var li2 = document.createElement('li');
-ul.appendChild(li1);
-ul.appendChild(li2);
-
-function hide(e){
-  // e.target refers to the clicked <li> element
-  // This is different than e.currentTarget which would refer to the parent <ul> in this context
-  e.target.style.visibility = 'hidden';
-}
-
-// Attach the listener to the list
-// It will fire when each <li> is clicked
-ul.addEventListener('click', hide, false);
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-event-target", "Event.target")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}{{Spec2("DOM2 Events")}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("api.Event.target")}}

- -

Compatibility notes

- -

On IE 6-8 the event model is different. Event listeners are attached with the non-standard {{domxref('EventTarget.attachEvent()')}} method. In this model, the event object has a {{domxref('Event.srcElement')}} property, instead of the target property, and it has the same semantics as Event.target.

- -
function hide(e) {
-  // Support IE6-8
-  var target = e.target || e.srcElement;
-  target.style.visibility = 'hidden';
-}
-
- -

See also

- - diff --git a/files/id/web/api/fetch_api/index.html b/files/id/web/api/fetch_api/index.html deleted file mode 100644 index ad64ee4558..0000000000 --- a/files/id/web/api/fetch_api/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Fetch API -slug: Web/API/Fetch_API -translation_of: Web/API/Fetch_API ---- -
{{DefaultAPISidebar("Fetch API")}}
- -

Fetch Data API menyediakan antarmuka untuk pemanggilan sumber daya data(termasuk di seluruh jaringan). Ini akan terasa familiar bagi siapa saja yang telah menggunakan {{DOMxRef("XMLHttpRequest")}}, tetapi untuk API yang terbaru menyediakan serangkaian fitur yang lebih kuat dan fleksibel.

- -

Konsep dan Penggunaan

- -

"Fetch" / pengambilan resource data menyediakan definisi umum yaitu objek{{DOMxRef("Request")}} dan {{DOMxRef("Response")}} atau permintaan dan tanggapan(dan hal-hal lain yang kaitannya dengan permintaan jaringan/"HTTP"). Ini akan memungkinkan "request" dan "response" tersebut untuk digunakan di mana pun mereka dibutuhkan di waktu selanjutnya, apakah itu untuk pekerja layanan/service workers(biasanya PWA), Cache API dan hal-hal serupa lainnya yang menangani atau mengubah permintaan dan tanggapan, ataupun juga segala jenis kasus penggunaan yang mungkin mengharuskan Anda untuk menghasilkan response/tanggapan Anda sendiri secara terprogram (baca aja:scr otomatis).

- -

Ini juga memberikan definisi untuk konsep yang berhubungan dengan request dan response seperti halnya : CORS dan sumber semantik header HTTP, yang menggantikan definisi mereka yang terpisah di topik lain (bukan disini bahasannya/beda topik).

- -

Untuk membuat permintaan dan mengambil sumber daya data, bisa menggunakan metode {{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}} ini. Metode ini diimplementasikan dalam beberapa antarmuka aplikasi, khususnya pada {{DOMxRef("Window")}} dan {{DOMxRef("WorkerGlobalScope")}}Ini membuatnya tersedia dalam hampir semua konteks yang mana anda mungkin menginginkan untuk mengambil sumber data / resource nya.

- -

Metode fetch() mengambil satu argumen yang wajib disertakan, path(sbg gambaran kalau di html : tag a dg atribut href) ke sumber data yang anda inginkan untuk mengambilnya. Hal ini mampu untuk mengembalikan hasil/return {{DOMxRef("Promise")}} yang memutuskan ke {{DOMxRef("Response")}} kepada permintaan itu sendiri, apakah hal tersebut berhasil atau tidak pada saat terjadi response/tanggapan sumber data. Anda juga bisa secara opsional mengirimkan objek pilihan initsebagai argumen keduanya (lihat {{DOMxRef("Request")}}).

- -

Setelah {{DOMxRef("Response")}} telah dipanggil, ada sejumlah metode yang tersedia untuk menentukan apa saja konten tubuh(pikirkan pada elemen html) dan bagaimana penanganannya (lihat {{DOMxRef("Body")}}).

- -

Anda juga bisa membuat permintaan dan response secara langsung menggunakan {{DOMxRef("Request.Request", "Request()")}}dan konstruktor {{DOMxRef("Response.Response", "Response()")}}, namun Anda tidak bisa melakukan ini secara langsung. Malahan, ini lebih cenderung sebagai hasil dari aksi yang dilakukan oleh API yang lainnya (misalnya, {{DOMxRef("FetchEvent.respondWith()")}} dari service workers (kalo loe yang main teknologinya PWA pasti tau coy)).

- -
-

Catatan : Cari tahu lebih lanjut mengenai penggunaan fitur Fetch API di cara menggunakan fetch , dan pelajari konsepnya di konsep dasar fetch .

-
- -

Batalkan fetch

- -

Web browser sudah mulai menambahkan dukungan eksperimental untuk antarmuka {{DOMxRef("AbortController")}} dan {{DOMxRef("AbortSignal")}}(alias API Abort), yang memungkinkan operasi seperti Fetch dan XHR untuk dibatalkan apabila mereka belum selesai secara sempurna dipanggil. Lihat halaman antarmuka untuk detail lebih lanjut.

- -

Browsers have started to add experimental support for the {{DOMxRef("AbortController")}} and {{DOMxRef("AbortSignal")}} interfaces (aka The Abort API), which allow operation

- -

 

- -

Antarmuka metode Fetch

- -
-
WindowOrWorkerGlobalScope.fetch()
-
Metode fetch() yang digunakan untuk mengambil sumber data.
-
Headers
-
Merupakan header respons / permintaan, memungkinkan Anda untuk menanyakannya(query) dan mengambil tindakan yang berbeda dimana ini tergantung pada hasilnya.
-
Request
-
Merupakan permintaan sumber data.
-
Response
-
Merupakan respons terhadap permintaan.
-
- -

Fetch mixin

- -
-
{{DOMxRef("Body")}}
-
Menyediakan metode yang berkaitan dengan konten pada respons / permintaan, memungkinkan Anda untuk menyatakan jenis kontennya dan bagaimana penanganannya.
-
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpesifikasiStatusKeterangan
{{SpecName("Fetch")}}{{Spec2("Fetch")}}Definisi awal
- -

Kompatibilitas Browser

- - - -

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

- -

Lihat juga untuk 

- - diff --git a/files/id/web/api/index.html b/files/id/web/api/index.html deleted file mode 100644 index bbbaf07d0a..0000000000 --- a/files/id/web/api/index.html +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Referensi API Web -slug: Web/API -tags: - - API - - Develop - - Web API -translation_of: Web/API ---- -

Saat menulis kode untuk Web menggunakan JavaScript, ada banyak API yang tersedia. Berikut adalah daftar semua antarmuka (atau dengan kata lain, tipe objek) yang dapat digunakan ketika mengembangkan aplikasi atau situs web.

- -
{{APIListAlpha}}
diff --git a/files/id/web/api/navigator/index.html b/files/id/web/api/navigator/index.html deleted file mode 100644 index 9d40d2eee4..0000000000 --- a/files/id/web/api/navigator/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: Navigator -slug: Web/API/Navigator -tags: - - API - - HTML DOM - - HTML-DOM - - Interface - - JavaScript - - NeedsTranslation - - Reference - - TopicStub - - Web Performance -translation_of: Web/API/Navigator ---- -

{{ apiref() }}

- -

Antarmuka Navigator mewakili negara dan identitas pengguna. Memungkinkan script untuk melakukan query dan mendaftarkan diri untuk melakukan suatu aktivitas.

- -

Objek Navigator dapat dipanggil menggunakan properti {{domxref("Window.navigator")}}.

- -

Properti

- -

Bukan turunan dari properti manapun, namun menginplementasikan yang didefinisikan di  {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorStorageUtils")}}, {{domxref("NavigatorCookies")}}, {{domxref("NavigatorConcurrentHardware")}}, {{domxref("NavigatorPlugins")}}, dan {{domxref("NavigatorUserMedia")}}.

- -

Standard

- -
-
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
-
Mengembalikan sebuah array yang berisi setiap objek {{domxref("VRDisplay")}} yang menyajikan ({{domxref("VRDisplay.ispresenting")}} adalah true).
-
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
-
Mengembalikan internal nama "code" browser. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
-
{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
-
Mengembalikan  {{domxref("DOMString")}} dengan nama official dari browser. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
-
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
-
Mengembalikan versi browser sebagai {{domxref("DOMString")}}. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
-
{{domxref("Navigator.battery")}} {{readonlyInline}}
-
Mengembalikan objek {{domxref("BatteryManager")}} yang memberikan informasi tentang status isi baterai.
-
{{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
-
Menyediakan sebuah objek {{domxref("NetworkInformation")}} yang berisi informasi tentang koneksi jaringan pada perangkat.
-
{{domxref("Navigator.geolocation")}} {{readonlyInline}}
-
Mengembalikan objek {{domxref("Geolocation")}} yang memungkinkan untuk mengakses lokasi perangkat.
-
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
-
Mengembalikan jumlah inti logical processor yag tersedia.
-
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
-
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
-
Mengembalikan {{domxref("DOMString")}} berdasarkan bahasa yang digunakan, biasanya bahasa UI pada browser. Nilai null akan dikembalikan jika tidak diketahui.
-
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
-
Mengembalikan sebuah array dari {{domxref("DOMString")}} berdasarkan bahasa yang diketahui pengguna, berdasarkan pengaturan.
-
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
-
Mengembalikan daftar {{domxref("MimeTypeArray")}} dari tipe MIME yang didukung oleh browser.
-
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
-
Mengembalikan sebuah {{domxref("Boolean")}} yang menunjukan apakah browser dalam keadaan online.
-
{{domxref("Navigator.oscpu")}}
-
Mengembalikan sebuah string berdasarkan sistem operasi.
-
{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
-
Mengembalikan objek {{domxref("Permissions")}} yang dapat digunakan untuk query dan membaharui status izin dari APIs yang di cakup di Permissions API.
-
{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.
-
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
-
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
-
Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose.
-
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
-
Returns the user agent string for the current browser.
-
{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
-
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
-
- -

Non-standard

- -
-

Firefox OS devices adds more non-standard properties. You can consult them on the Firefox OS Navigator extensions article.

-
- -

{{domxref("Navigator.buildID")}} {{non-standard_inline}}

- -
-
Returns the build identifier of the browser (e.g., "2006090803").
-
{{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}
-
Returns a boolean indicating whether cookies are enabled in the browser or not.
-
{{domxref("Navigator.credentials")}} {{non-standard_inline}}
-
Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. 
-
{{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}
-
Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.
-
{{domxref("Navigator.id")}} {{non-standard_inline}}
-
Returns the {{domxref("window.navigator.id", "id")}} object which you can use to add support for BrowserID to your web site.
-
{{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}
-
Returns a reference to the {{domxref("MediaDevices")}} interface.
-
{{domxref("Navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
- {{domxref("Navigator.webkitNotification")}}
-
Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
-
{{domxref("Navigator.mozSocial")}} {{non-standard_inline}}
-
The Object, returned by the navigator.mozSocial property, is available within the social media provider's panel to provide functionality it may need.
-
{{domxref("Navigator.presentation")}} {{non-standard_inline}}
-
Returns a reference to the {{domxref("Presentation")}} API.
-
{{domxref("Navigator.productSub")}} {{non-standard_inline}}
-
Returns the build number of the current browser (e.g., "20060909").
-
{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
-
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
-
{{domxref("Navigator.standalone")}} {{non-standard_inline}}
-
Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
-
{{domxref("Navigator.vendor")}} {{non-standard_inline}}
-
Returns the vendor name of the current browser (e.g., "Netscape6").
-
{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}
-
Returns the vendor version number (e.g. "6.1").
-
{{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}
-
Returns a PointerLock object for the Mouse Lock API.
-
- -

Methods

- -

Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NavigatorStorageUtils")}}.

- -

Standard

- -
-
{{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}
-
Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
-
{{domxref("Navigator.getUserMedia", "NavigatorUserMedia.getUserMedia()")}}
-
After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
-
{{domxref("Navigator.registerContentHandler()")}}
-
Allows web sites to register themselves as a possible handler for a given MIME type.
-
{{domxref("Navigator.registerProtocolHandler()")}}
-
Allows web sites to register themselves as a possible handler for a given protocol.
-
{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}
-
Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
-
{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}
-
Used to asynchronously transfer small HTTP data from the User Agent to a web server.
-
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}
-
Returns false. JavaScript taint/untaint functions removed in JavaScript 1.2.
-
{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}
-
Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
-
- -

Non-standard

- -
-

Firefox OS devices adds more non-standard methods. You can consult them on the Firefox OS Navigator extensions article.

-
- -

{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}

- -
-
Lets code check to see if the document at a given URI is available without using the network.
-
{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}
-
Allows in-app payment.
-
diff --git a/files/id/web/api/navigator/mediadevices/index.html b/files/id/web/api/navigator/mediadevices/index.html deleted file mode 100644 index b51d697dd9..0000000000 --- a/files/id/web/api/navigator/mediadevices/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Navigator.mediaDevices -slug: Web/API/Navigator/mediaDevices -translation_of: Web/API/Navigator/mediaDevices ---- -
{{APIRef("Media Capture and Streams")}}
- -

The Navigator.mediaDevices read-only property returns a {{domxref("MediaDevices")}} object, which provides access to connected media input devices like cameras and microphones, as well as screen sharing.

- -

Syntax

- -
var mediaDevices = navigator.mediaDevices;
-
- -

Return value

- -

The {{domxref("MediaDevices")}} singleton object. Usually, you just use this object's members directly, such as by calling {{domxref("navigator.mediaDevices.getUserMedia()")}}.

- -

Spesifikasi

- - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('Media Capture', '#mediadevices', 'NavigatorUserMedia.mediaDevices')}}{{Spec2('Media Capture')}}Initial definition.
- -

Browser compatibility

- - - -

{{Compat("api.Navigator.mediaDevices")}}

- -

Lihat juga

- - diff --git a/files/id/web/api/navigator/serviceworker/index.html b/files/id/web/api/navigator/serviceworker/index.html deleted file mode 100644 index 2599ecf9a2..0000000000 --- a/files/id/web/api/navigator/serviceworker/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Navigator.serviceWorker -slug: Web/API/Navigator/serviceWorker -tags: - - API - - Reference - - Service Worker -translation_of: Web/API/Navigator/serviceWorker ---- -

{{APIRef("Service Workers API")}}

- -

Navigator.serviceWorker adalah properti yang hanya bisa dibaca, mengembalikan objek {{domxref("ServiceWorkerContainer")}} untuk dokumen terkait, yang memberikan akses untuk registrasi, penghapusan, upgrade, dan berkomunikasi dengan {{domxref("ServiceWorker")}}.

- -

Sintaks

- -
var workerContainerInstance = navigator.serviceWorker;
-
- -

Nilai

- -

{{domxref("ServiceWorkerContainer")}}.

- -

Spesifikasi

- - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('Service Workers', '#navigator-service-worker', 'navigator.serviceWorker')}}{{Spec2('Service Workers')}}Initial definition.
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
-
- -

[1] Service workers (dan Push) telah di non-aktifkan di Firefox 45 Extended Support Release (ESR.)

- -

Lihat Juga

- - diff --git a/files/id/web/api/push_api/index.html b/files/id/web/api/push_api/index.html deleted file mode 100644 index 7b4fe1a249..0000000000 --- a/files/id/web/api/push_api/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: API Push -slug: Web/API/Push_API -translation_of: Web/API/Push_API -original_slug: Web/API/API_Push ---- -
{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}
- -

API Push memberikan aplikasi web kemampuan menerima pesan yang didorong oleh peladen ke dalam agen pengguna, baik bila aplikasi berada di permukaan atau baru dimuat. API Push memungkinkan pengembang memberikan pemberitahuan dan pembaruan tak sinkron ke pengguna yang mengizinkan. Hal ini memberikan hasil pendekatan yang lebih baik untuk muatan baru yang terus berubah.

- -
-

Catatan: Dokumentasi ini melingkupi spesifikasi API Push W3C. Bila Anda mencari dokumentasi untuk mekanisme berpemilik dari Firefox OS, lihat Push Sederhana.

-
- -

Push concepts and usage

- -

For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications using {{domxref("PushManager.subscribe()")}}.

- -

The resulting {{domxref("PushSubscription")}} includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data.

- -

The service worker will be started as necessary to handle incoming push messages, which are delivered to the {{domxref("ServiceWorkerGlobalScope.onpush")}} event handler. This allows apps to react to push messages being received, for example by displaying a notification (using {{domxref("ServiceWorkerRegistration.showNotification()")}}.)

- -

Each subscription is unique to a service worker.  The endpoint for the subscription is a unique capability URL: knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be able to send push messages to your application.

- -

Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different schemes for handling this — there is currently no standard mechanism. Firefox allows a limited number (quota) of push messages to be sent to an application, although Push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. In comparison, Chrome applies no limit but requires that every push message causes a notification to be displayed.

- -
-

Note: As of Gecko 44, the allowed quota of push messages per application is not incremented when a new notification fires when another is still visible, for a period of three seconds. This handles cases where a burst of notifications is received, and not all generate a visible notification.

-
- -
-

Note: Chrome currently requires you to set up a project on Google Cloud Messaging to send push messages, and use the associated project number and API key when sending push notifications. It also requires an app manifest with some special parameters to use this service. This restriction will hopefully be removed in the future.

-
- -

Interfaces

- -
-
{{domxref("PushEvent")}}
-
Represents a push action sent to the global scope of a {{domxref("ServiceWorker")}}. It contains information sent from an application to a {{domxref("PushSubscription")}}.
-
{{domxref("PushManager")}}
-
Provides a way to receive notifications from third-party servers as well as request URLs for push notifications. This interface has replaced functionality offered by the obsolete {{domxref("PushRegistrationManager")}} interface.
-
{{domxref("PushMessageData")}}
-
Provides access to push data sent by a server, and includes methods to manipulate the received data.
-
{{domxref("PushSubscription")}}
-
Provides a subcription's URL endpoint and allows unsubscription from a push service.
-
- -

Service worker additions

- -

The following additions to the Service Worker API have been specified in the Push API spec, to provide an entry point for using Push messages, and  to monitor and respond to push and subscription change events.

- -
-
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
-
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.
-
{{domxref("ServiceWorkerGlobalScope.onpush")}}
-
An event handler fired whenever a {{Event("push")}} event occurs; that is, whenever a server push message is received.
-
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
-
An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("Push API")}}{{Spec2("Push API")}}Initial definition
- -

Browser Compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1]{{CompatNo}}[2]{{CompatUnknown}}{{CompatUnknown}}
{{domxref("PushEvent.data")}},
- {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatGeckoDesktop(44.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
{{domxref("PushEvent.data")}},
- {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

[1] Currently available only on desktop versions of Firefox; also, push messages are only delivered when Firefox is running.

- -

[2] This is currently not implemented. See the Microsoft Edge status information.

- -

See also

- - diff --git a/files/id/web/api/service_worker_api/index.html b/files/id/web/api/service_worker_api/index.html deleted file mode 100644 index 345f183563..0000000000 --- a/files/id/web/api/service_worker_api/index.html +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Service Worker API -slug: Web/API/Service_Worker_API -tags: - - API - - Landing - - NeedsTranslation - - Offline - - Overview - - Reference - - Service Workers - - TopicStub - - Workers -translation_of: Web/API/Service_Worker_API ---- -
-

{{ServiceWorkerSidebar}}

- -

{{ SeeCompatTable() }}

- -

Service workers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.

-
- -

Service worker concepts and usage

- -

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

- -

A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is not blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker.

- -

Service workers only run over HTTPS, for security reasons. Having modified network requests wide open to man in the middle attacks would be really bad.

- -
-

Note: Service Workers win over previous attempts in this area such as AppCache because they don't make assumptions about what you are trying to do and then break when those assumptions are not exactly right; you have granular control over everything.

-
- -
-

Note: Service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.

-
- -

Registration

- -

A service worker is first registered using the {{domxref("ServiceWorkerContainer.register()")}} method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.

- -

Download, install and activate

- -

At this point, your service worker will observe the following lifecycle:

- -
    -
  1. Download
  2. -
  3. Install
  4. -
  5. Activate
  6. -
- -

The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.

- -

After that it is downloaded every 24 hours or so. It *may* be downloaded more frequently, but it must be downloaded every 24h to prevent bad scripts from being annoying for too long.

- -

Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.

- -

If this is the first time a service worker has been made available, installation is attempted, then after a successful installation it is activated.

- -

If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates (becoming the active worker).

- -

You can listen out for the {{domxref("InstallEvent")}}; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

- -

There is also an activate event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.

- -

Your service worker can respond to requests using the {{domxref("FetchEvent")}} event. You can modify the response to these requests in any way you want, using the {{domxref("FetchEvent.respondWith") }} method.

- -
-

Note: Because oninstall/onactivate could take a while to complete, the service worker spec provides a waitUntil method that, when called oninstall or onactivate, passes a promise. Functional events are not dispatched to the service worker until the promise successfully resolves.

-
- -

For a complete tutorial to show how to build up your first basic example, read Using Service Workers.

- -

Other use case ideas

- -

Service workers are also intended to be used for such things as:

- - - -

In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

- - - -

Interfaces

- -
-
{{domxref("Cache") }}
-
Represents the storage for {{domxref("Request")}} / {{domxref("Response")}} object pairs that are cached as part of the {{domxref("ServiceWorker")}} life cycle.
-
{{domxref("CacheStorage") }}
-
Represents the storage for {{domxref("Cache")}} objects. It provides a master directory of all the named caches that a {{domxref("ServiceWorker")}} can access and maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.
-
{{domxref("Client") }}
-
Represents the scope of a service worker client. A service worker client is either a document in a browser context or a {{domxref("SharedWorker")}}, which is controlled by an active worker.
-
{{domxref("Clients") }}
-
Represents a container for a list of {{domxref("Client")}} objects; the main way to access the active service worker clients at the current origin.
-
{{domxref("ExtendableEvent") }}
-
Extends the lifetime of the install and activate events dispatched on the {{domxref("ServiceWorkerGlobalScope")}} as part of the service worker lifecycle. This ensures that any functional events (like {{domxref("FetchEvent")}}) are not dispatched to the {{domxref("ServiceWorker")}} until it upgrades database schemas, deletes outdated cache entries, etc.
-
{{domxref("ExtendableMessageEvent") }}
-
The event object of a {{event("message_(ServiceWorker)","message")}} event fired on a service worker (when a channel message is received on the {{domxref("ServiceWorkerGlobalScope")}} from another context) — extends the lifetime of such events.
-
{{domxref("FetchEvent") }}
-
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onfetch")}} handler, FetchEvent represents a fetch action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. It contains information about the request and resulting response, and provides the {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}} method, which allows us to provide an arbitrary response back to the controlled page.
-
{{domxref("InstallEvent") }}
-
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the InstallEvent interface represents an install action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. As a child of {{domxref("ExtendableEvent")}}, it ensures that functional events such as {{domxref("FetchEvent")}} are not dispatched during installation. 
-
{{domxref("Navigator.serviceWorker") }}
-
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
-
{{domxref("NotificationEvent") }}
-
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} handler, the NotificationEvent interface represents a notification click event that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.
-
{{domxref("ServiceWorker") }}
-
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.
-
{{domxref("ServiceWorkerContainer") }}
-
Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
-
{{domxref("ServiceWorkerGlobalScope") }}
-
Represents the global execution context of a service worker.
-
{{domxref("ServiceWorkerMessageEvent")}}
-
Contains information about an event sent to a {{domxref("ServiceWorkerContainer")}} target. 
-
{{domxref("ServiceWorkerRegistration") }}
-
Represents a service worker registration.
-
{{domxref("SyncEvent")}} {{non-standard_inline}}
-
-

The SyncEvent interface represents a sync action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a ServiceWorker. 

-
-
{{domxref("SyncManager")}} {{non-standard_inline}}
-
Provides an interface for registering and listing sync registrations.
-
{{domxref("WindowClient") }}
-
Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of {{domxref("Client")}} object, with some additional methods and properties available.
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
- -

Browser compatibility

- -
{{ CompatibilityTable() }}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}24{{ CompatNo() }}
install/activate events{{ CompatChrome(40.0) }}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
- respondWith()
{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache -

{{CompatChrome(42.0)}}

-
{{ CompatGeckoDesktop("39.0") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support {{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
 install/activate events{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
- respondWith()
{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("39.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

- -

See also

- - diff --git a/files/id/web/api/service_worker_api/using_service_workers/index.html b/files/id/web/api/service_worker_api/using_service_workers/index.html deleted file mode 100644 index b88643f6ed..0000000000 --- a/files/id/web/api/service_worker_api/using_service_workers/index.html +++ /dev/null @@ -1,539 +0,0 @@ ---- -title: Menggunakan Service Workers -slug: Web/API/Service_Worker_API/Using_Service_Workers -tags: - - Paduan - - ServiceWorker - - dasar -translation_of: Web/API/Service_Worker_API/Using_Service_Workers ---- -

{{ServiceWorkerSidebar}}

- -

{{ SeeCompatTable() }}

- -
-

Artikel ini memberikan informasi mengenai cara memulai dan menggunakan Service Workers, Termasuk arsitektur dasar, mendaftarkan service worker, penginstalan dan proses aktivasi service worker, memperbaharui service worker, kontrol cache dan custom response, Semuanya dalam konteks aplikasi sederhana dengan fungsi offline. 

-
- -

Premis Service Workers

- -

Salah satu masalah utama yang dialami pengguna web selama bertahun - tahun adalah hilangnya konektivitas. Bahkan aplikasi terbaik didunia sekalipun akan memberikan pengalaman pengguna yang buruk jika tidak bisa di muat atau di download. Berbagai upaya menciptakan teknologi telah dilakukan untuk memecahkan masalah tersebut, Agar halaman Offline dapat digunakan, dan beberapa masalah telah diselesaikan.Tapi masalah utamanya masih belum ada mekanisame kontrol yang terbaik untuk semua permintaan aset cache dan kostum jaringan.
-
- Pada upaya sebelumnya — AppCache — dilihat sebagai ide yang bagus karena disana anda juga bisa menentukan aset untuk dicache dengan mudah. Namun, itu membuat asumsi tentang ketika anda mencoba dan kemudian pecah dengan mengerikan ketika aplikasi anda tidak mengikuti asumsi premis. Baca artikel Jake Archibald's Application Cache is a Douchebag untuk lebih detail.

- -
-

Catatan: Pada firefox 44, ketika AppCache digunakan untuk menyediakan layanan offline untuk suatu halaman, pesan peringatan sekarang akan ditampilkan di console menyarankan pengembang untuk menggunakan Service workers  ({{bug("1204581")}}.)

-
- -

Service worker seharusnya telah memecahkan masalah ini. Syntax pada service worker lebih kompleks di bandingkan AppCache, tapi kesamaanya adalah anda bisa menggunkan javascript untuk mengontrol AppCache anda secara tersirat dengan derajat grunality yang lebih bagus, memungkinkan anda untuk menangani masalah ini dan banyak lagi. Dengan menggunakan Service worker anda bisa mengatur aplikasi untuk menggunakan aset utama, sehingga memberikan pengalaman utama bahkan saat offline, sebelum mendapatkan lebih banyak data dari jaringan (biasa disebut sebagai Offline First). Ini sudah tersedia dengan aplikasi asli, yang merupakan salah satu alasan utama aplikasi asli sering dipilih lebih dari aplikasi web.

- -

Persiapan bermain dengan service worker

- -

Banyak fitur service worker saat ini telah di aktifkan secara default pada browser versi terbaru yang mendukung. Tapi jika anda menemui kode demo tidak bekerja pada versi browser anda, mungkin anda perlu mengaktifkan preferensi:

- - - -

Anda perlu menyajikan kode dengan menggunakan HTTPS — Service Workers dibatasi dengan hanya dapat di jalankan pada HTTPS untuk alasan keamanan. Github merupakan salah satu tempat yang di sarankan untuk bereksperimen, karena mendukung HTTPS.

- -

Arsitektur dasar

- -

Dengan service workers, langkah - langkah umum berikut perlu diamati untuk konfigurasi dasar:

- -
    -
  1. URL service worker diambil di daftarkan melalui {{domxref("serviceWorkerContainer.register()")}}.
  2. -
  3. Jika sukses, service worker dijalankan di {{domxref("ServiceWorkerGlobalScope") }}; pada dasarnya ini merupakan hal yang sepesial dari konteks worker, menjalankan tread script utama untuk pengeksekusian, tanpa dukungan akses DOM.
  4. -
  5. Sekarang service worker telah siap untuk memproses event.
  6. -
  7. Instalasai service worker dicoba ketika service worker mengontrol halaman yang diakses setelah dan sebelumnya. Even Install akan selalu di kirim pertama kali ke service workerr ( ini bisa digunakan untuk memulai proses untuk mengumpulkan IndexedDB, dan mencache aset situs). Sama halnya seperti prosedur penginstalan asli atau aplikasi firefox OS — memungkinkan semuanya tersedia untuk digunakan secara offline.
  8. -
  9. Ketika handler oninstall selesai, service worker ditetapkan untuk diinstall.
  10. -
  11. Selanjutnya adalah aktivasi. Ketika service worker terinstall, selanjutnya akan menerima event activate. Penggunaan utama dari onactivate adalah untuk membersihkan sumberdaya yang digunakan pada versi sebelumnya.
  12. -
  13. Service Worker sekarang dapat mengontrol halaman, tapi hanya yang di buka setelah register() telah sukses. misal dokumen mulai aktif dengan atau tanpa Service Worker dan menjaganya selama masih digunakan. Jadi dokumen harus di muat ulang agar benar - benar terkontrol.
  14. -
- -

- -

Grafik dibawah menunjukan ringkasan dari event yang tersedia pada service worker:

- -

install, activate, message, fetch, sync, push

- -

Promis

- -

Promis adalah mekanisme yang sebagian besar digunakan untuk menjalankan operasi secara asinkron, dengan bergantung pada pencapaian satu dan lainnya. Ini merupakan pusat dari cara kerja service workers.
-
- Promis bisa digunakan untuk melakukan banyak hal, tapi untuk saat ini, yang perlu anda tahu adalah jika sesuatu yang mengembalikan promise, anda bisa menambahkan.then() di akhir dan menambahkan callback di dalamnya untuk mengetahui apakah berhasil, gagal da lainnya., atau anda bisa menambahkan .catch() di akhir jika anda ingin menambahkan calback status gagal.

- -

Mari bandingkan kesamaan struktur callback tradisional synchronous dan promise asynchronous.

- -

sync

- -
try {
-  var value = myFunction();
-  console.log(value);
-} catch(err) {
-  console.log(err);
-}
- -

async

- -
myFunction().then(function(value) {
-  console.log(value);
-  }).catch(function(err) {
-  console.log(err);
-});
- -

Pada contoh pertama, kita perlu mengunggu myFunction() untuk dijalankan dan mengembalikan nilai sebelum kode lain bisa dijalankan. Pada contoh kedua, myFunction() mengembalikan promise untuk nilai, kemudian semua kode dapat di bawa untuk dapat dijalankan. Ketika promise diselesaikan, kode didalamnya bisa dijalankan secara asynchronously.
-
- Sebagai contoh nyata — jika kita ingin memuat gambar secara dinamic, tapi kita ingin memastikan bahwa gambar tersebut di muat terlebih dahulu sebelum di tampilkan? Hal standar ini yang ingin dilakukan, tapi ini akan sedikit sulit. Kita bisa mengunakan .onload untuk hanya menampilkan gambar setelah di muat, tapi bagaimana dengan event yang memulai sebelum kita memulai melacaknya ? kita bisa mencoba melakukannya dengan menggunakan.complete, tapi ini tetap tidak foolproof, dan bagaimana dengan lebih dari satu gambar? Dan, ummm, ini tetap synchronous, Jadi di blok di tread utama.
-
- Gantinya, kita bisa membuat promis kita sendiri untuk mengatasi kasus seperi ini. (Lihat contoh Promises test untuk kode sumber, atau Lihat cara kerja secara live.)

- -

{{note("Implementasi service worker akan mengutamakan menggunakan caching dan onfetch daripada XMLHttpRequest API. Fitur tersebut tidak di gunakan disini jadi anda hanya fokus pada penggunaan Promises.")}}

- -
function imgLoad(url) {
-  return new Promise(function(resolve, reject) {
-    var request = new XMLHttpRequest();
-    request.open('GET', url);
-    request.responseType = 'blob';
-
-    request.onload = function() {
-      if (request.status == 200) {
-        resolve(request.response);
-      } else {
-        reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
-      }
-    };
-
-    request.onerror = function() {
-      reject(Error('There was a network error.'));
-    };
-
-    request.send();
-  });
-}
- -

Kita mengembalikan promis baru menggunakan konstruktor Promise(), di mana menggunakan argumen sebagai fungsi callback dengan parameter resolve dan reject. DImanapung di fungsi, kita perlu mendefinisikan apa yang terjadi untuk promise yang diselesaikan secara sukses atau ditolak — pada kasus ini mengembalikan status 200 OK atau tidak — dan kemudian memanggil  resolve ketika sukses, atau reject jika gagal. Semua konten dari fungsi ini adalah perangkat dasar XHR, jadi kita tidak perlu khawatir untuk saat ini.

- -

Ketika memanggil fungsi imgLoad(), kita memanggilnya dengan menggunakan url gambar yang akan dimuat, seperti yang kita harapkan, namun kodenya sedikit berbeda:

- -
var body = document.querySelector('body');
-var myImage = new Image();
-
-imgLoad('myLittleVader.jpg').then(function(response) {
-  var imageURL = window.URL.createObjectURL(response);
-  myImage.src = imageURL;
-  body.appendChild(myImage);
-}, function(Error) {
-  console.log(Error);
-});
- -

Pada akhir pemanggilan fungsi, kita menggabungkan promise method then(), dimana terdiri dari dua fungsi — yang pertama akan di eksekusi ketika promise berhasil di selesaikan, dan yang kedua akan dipanggil ketika promise di tolak. Pada penyelesaian kasus, kita menampilkan gambar di dalam myImage dan menambahkannya ke body (dengan argumen request.response yang berada di dalam method resolve); pada kasus ditolak kita mengembalikan error di console.

- -

Semua terjadi secara asynchronously.

- -
-

Catatan: Anda juga bisa menggabungkan panggilan promise secara bersamaan, Misal:
- myPromise().then(success, failure).then(success).catch(failure);

-
- -
-

Catatan: Anda bisa mendapatkan lebih banyak informasi tentang promise dengan membaca tulisan Jake Archibald’s excellent JavaScript Promises: there and back again.

-
- -

Demo service workers

- -

Sebagai demonstrasi hanya sekedar dasar pendaftaran dan penginstalan service worker, kita membuat sebuah demo sederhana dengan nama sw-test, berupa galeri gambar Star wars Lego. Mengunakan fungsi dengan promise untuk membaca data gambar dari sebuah objek JSON dan memuat gambar menggunakan Ajax, Sebelum menamilkan gambar pada halaman. Kita akan semuanya tetap simple dan statis untuk saat ini. Di sini pendaftaran, instalasi, dan akativasi sebuah service worker, dan ketika semua spec di dukung oleh browsers maka semua file yang diperukan akan dicache untuk di muat secara offline!

- -


-
-
- Anda bisa melihat source code di GitHub, dan Melihat contoh secara live. The one bit we’ll call out here is the promise (see app.js lines 17-42), which is a modified version of what you read about above, in the Promises test demo. It is different in the following ways:

- -
    -
  1. In the original, we only passed in a URL to an image we wanted to load. In this version, we pass in a JSON fragment containing all the data for a single image (see what they look like in image-list.js). This is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. If you just passed in the url, and then tried to access the other items in the JSON separately when the for() loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.)
  2. -
  3. We actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js lines 26-29). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.
  4. -
  5. To access the resolved promise values, we then access this function as you’d then expect (see app.js lines 55-59.) This may seem a bit odd at first, but this is the way promises work.
  6. -
- -

Enter Service workers

- -

Now let’s get on to service workers!

- -

Mendaftarkan worker

- -

The first block of code in our app’s JavaScript file — app.js — is as follows. This is our entry point into using service workers.

- -
if ('serviceWorker' in navigator) {
-  navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {
-    // registration worked
-    console.log('Registration succeeded. Scope is ' + reg.scope);
-  }).catch(function(error) {
-    // registration failed
-    console.log('Registration failed with ' + error);
-  });
-};
- -
    -
  1. The outer block performs a feature detection test to make sure service workers are supported before trying to register one.
  2. -
  3. Next, we use the {{domxref("ServiceWorkerContainer.register()") }} function to register the service worker for this site, which is just a JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.)
  4. -
  5. The scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified '/sw-test/', which means all content under the app's origin. If you leave it out, it will default to this value anyway, but we specified it here for illustration purposes.
  6. -
  7. The .then() promise function is used to chain a success case onto our promise structure.  When the promise resolves successfully, the code inside it executes.
  8. -
  9. Finally, we chain a .catch() function onto the end that will run if the promise is rejected.
  10. -
- -

This registers a service worker, which runs in a worker context, and therefore has no DOM access. You then run code in the service worker outside of your normal pages to control their loading.
-
- A single service worker can control many pages. Each time a page within your scope is loaded, the service worker is installed against that page and operates on it. Bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn’t get its own unique worker.

- -
-

Note: Your service worker functions like a proxy server, allowing you to modify requests and responses, replace them with items from its own cache, and more.

-
- -
-

Note: One great thing about service workers is that if you use feature detection like we’ve shown above, browsers that don’t support service workers can just use your app online in the normal expected fashion. Furthermore, if you use AppCache and SW on a page, browsers that don’t support SW but do support AppCache will use that, and browsers that support both will ignore the AppCache and let SW take over.

-
- -

Kenapa service worker saya gagal didaftarkan?

- -

Hal tersebut bisa terjadi karena alasan berikut:

- -
    -
  1. Anda tidak menjalankan aplikasi dari HTTPS.
  2. -
  3. Path dari file service worker anda tidak ditulis dengan benar — seharusnya di tulis relatif terhadap origin, bukan root dari direktori aplikasi anda. Pada contoh, worker berada di https://mdn.github.io/sw-test/sw.js, dan root aplikasi di https://mdn.github.io/sw-test/. Namun path harus ditulis /sw-test/sw.js, bukan /sw.js.
  4. -
  5. The service worker being pointed to is on a different origin to that of your app. This is also not allowed.
  6. -
- -

- -

Also note:

- - - -

Install dan activasi: mengumpulkan cache

- -

Setelah service worker anda terdaftar, browser akan menginstall dan mengaktifkan service worker untuk halaman/situs anda.
-
- Event instal dijalankan ketika install selesai dengan sukses. Event install biasanya digunakan oleh browser untuk mengumpulkan cache offline dari aset yang akan digunakan untuk menjalankan aplikasi anda secara offline. Untuk melakukannya, kita menggunakan Storage API dari Service Worker — {{domxref("cache")}} —  global pada service worker yang memungkinkan kita menympan aset yang diterima dari response, dan di sandikan berdasarkan request. API ini sama halnya dengan cache pada browser umumnya, tapi lebih spesifik ke domain. Ini persis hinga anda tidak menginginkan — anda punya kontrol penuh.

- -
-

Note: The Cache API is not supported in every browser. (See the {{anch("Browser support")}} section for more information.) If you want to use this now, you could consider using a polyfill like the one available in Google's Topeka demo, or perhaps store your assets in IndexedDB.

-
- -

Let’s start this section by looking at a code sample — this is the first block you’ll find in our service worker:

- -
this.addEventListener('install', function(event) {
-  event.waitUntil(
-    caches.open('v1').then(function(cache) {
-      return cache.addAll([
-        '/sw-test/',
-        '/sw-test/index.html',
-        '/sw-test/style.css',
-        '/sw-test/app.js',
-        '/sw-test/image-list.js',
-        '/sw-test/star-wars-logo.jpg',
-        '/sw-test/gallery/',
-        '/sw-test/gallery/bountyHunters.jpg',
-        '/sw-test/gallery/myLittleVader.jpg',
-        '/sw-test/gallery/snowTroopers.jpg'
-      ]);
-    })
-  );
-});
- -
    -
  1. Here we add an install event listener to the service worker (hence this), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the Service Worker will not install until the code inside waitUntil() has successfully occurred.
  2. -
  3. Inside waitUntil() we use the caches.open() method to create a new cache called v1, which will be version 1 of our site resources cache. This returns a promise for a created cache; once resolved, we then call a function that calls addAll() on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.
  4. -
  5. If the promise is rejected, the install fails, and the worker won’t do anything. This is ok, as you can fix your code and then try again the next time registration occurs.
  6. -
  7. After a successful installation, the service worker activates. This doesn’t have much of a distinct use the first time your service worker is installed/activated, but it means more when the service worker is updated (see the {{anch("Updating your service worker") }} section later on.)
  8. -
- -
-

Note: localStorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.

-
- -
-

Note: IndexedDB can be used inside a service worker for data storage if you require it.

-
- -

Custom responses to requests

- -

Now you’ve got your site assets cached, you need to tell service workers to do something with the cached content. This is easily done with the fetch event.

- -

- -

A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.)

- -

You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic.

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    // magic goes here
-  );
-});
- -

We could start by simply responding with the resource whose url matches that of the network request, in each case:

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    caches.match(event.request);
-  );
-});
- -

caches.match(event.request) allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests.

- -

Let’s look at a few other options we have when defining our magic (see our Fetch API documentation for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)

- -
    -
  1. -

    The {{domxref("Response.Response","Response()")}} constructor allows you to create a custom response. In this case, we are just returning a simple text string:

    - -
    new Response('Hello from your friendly neighbourhood service worker!');
    -
  2. -
  3. -

    This more complex Response below shows that you can optionally pass a set of headers in with your response, emulating standard HTTP response headers. Here we are just telling the browser what the content type of our synthetic response is:

    - -
    new Response('
    - -

    Hello from your friendly neighbourhood service worker!

    - ', { headers: { 'Content-Type': 'text/html' } })
  4. -
  5. -

    If a match wasn’t found in the cache, you could tell the browser to simply {{domxref("GlobalFetch.fetch","fetch")}} the default network request for that resource, to get the new resource from the network if it is available:

    - -
    fetch(event.request)
    -
  6. -
  7. -

    If a match wasn’t found in the cache, and the network isn’t available, you could just match the request with some kind of default fallback page as a response using {{domxref("CacheStorage.match","match()")}}, like this:

    - -
    caches.match('/fallback.html');
    -
  8. -
  9. -

    You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:

    - -
    event.request.url
    -event.request.method
    -event.request.headers
    -event.request.body
    -
  10. -
- -

Recovering failed requests

- -

So caches.match(event.request) is great when there is a match in the service worker cache, but what about cases when there isn’t a match? If we didn’t provide any kind of failure handling, our promise would reject and we would just come up against a network error when a match isn’t found.

- -

Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    caches.match(event.request).catch(function() {
-      return fetch(event.request);
-    })
-  );
-});
- -

If the promise rejects, the catch() function returns the default network request for the resource instead, meaning that those who have network available can just load the resource from the server.

- -

If we were being really clever, we would not only request the resource from the network; we would also save it into the cache so that later requests for that resource could be retrieved offline too! This would mean that if extra images were added to the Star Wars gallery, our app could automatically grab them and cache them. The following would do the trick:

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    caches.match(event.request).catch(function() {
-      return fetch(event.request).then(function(response) {
-        return caches.open('v1').then(function(cache) {
-          cache.put(event.request, response.clone());
-          return response;
-        });
-      });
-    })
-  );
-});
- -

Here we return the default network request with return fetch(event.request), which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using caches.open('v1'); this also returns a promise. When that promise resolves, cache.put() is used to add the resource to the cache. The resource is grabbed from event.request, and the response is then cloned with response.clone() and added to the cache. The clone is put in the cache, and the original response is returned to the browser to be given to the page that called it.

- -

Why? This is because request and response streams can only be read once.  In order to return the response to the browser and put it in the cache we have to clone it. So the original gets returned to the browser and the clone gets sent to the cache.  They are each read once.

- -

The only trouble we have now is that if the request doesn’t match anything in the cache, and the network is not available, our request will still fail. Let’s provide a default fallback so that whatever happens, the user will at least get something:

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    caches.match(event.request).catch(function() {
-      return fetch(event.request).then(function(response) {
-        return caches.open('v1').then(function(cache) {
-          cache.put(event.request, response.clone());
-          return response;
-        });
-      });
-    }).catch(function() {
-      return caches.match('/sw-test/gallery/myLittleVader.jpg');
-    })
-  );
-});
- -

We have opted for this fallback image because the only updates that are likely to fail are new images, as everything else is depended on for installation in the install event listener we saw earlier.

- -

Updated code pattern suggestion

- -

This uses more standard promise chaining and returns the response to the document without having to wait for caches.open() to resolve:

- -
this.addEventListener('fetch', function(event) {
-  var response;
-  event.respondWith(caches.match(event.request).catch(function() {
-    return fetch(event.request);
-  }).then(function(r) {
-    response = r;
-    caches.open('v1').then(function(cache) {
-      cache.put(event.request, response);
-    });
-    return response.clone();
-  }).catch(function() {
-    return caches.match('/sw-test/gallery/myLittleVader.jpg');
-  }));
-});
- -

Membaharui service worker

- -

If your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates.

- -

You’ll want to update your install event listener in the new service worker to something like this (notice the new version number):

- -
this.addEventListener('install', function(event) {
-  event.waitUntil(
-    caches.open('v2').then(function(cache) {
-      return cache.addAll([
-        '/sw-test/',
-        '/sw-test/index.html',
-        '/sw-test/style.css',
-        '/sw-test/app.js',
-        '/sw-test/image-list.js',
-
-             …
-
-              // include other new resources for the new version...
-      ]);
-    });
-  );
-});
- -

While this happens, the previous version is still responsible for fetches. The new version is installing in the background. We are calling the new cache v2, so the previous v1 cache isn't disturbed.

- -

When no pages are using the current version, the new worker activates and becomes responsible for fetches.

- -

Deleting old caches

- -

You also get an activate event. This is a generally used to do stuff that would have broken the previous version while it was still running, for example getting rid of old caches. This is also useful for removing data that is no longer needed to avoid filling up too much disk space — each browser has a hard limit on the amount of cache storage that a given service worker can use. The browser does its best to manage disk space, but it may delete the Cache storage for an origin.  The browser will generally delete all of the data for an origin or none of the data for an origin.

- -

Promises passed into waitUntil() will block other events until completion, so you can rest assured that your clean-up operation will have completed by the time you get your first fetch event on the new cache.

- -
this.addEventListener('activate', function(event) {
-  var cacheWhitelist = ['v2'];
-
-  event.waitUntil(
-    caches.keys().then(function(keyList) {
-      return Promise.all(keyList.map(function(key) {
-        if (cacheWhitelist.indexOf(key) === -1) {
-          return caches.delete(key);
-        }
-      }));
-    })
-  );
-});
- -

Dev tools

- -

Chrome has chrome://inspect/#service-workers, which shows current service worker activity and storage on a device, and chrome://serviceworker-internals, which shows more detail and allows you to start/stop/debug the worker process. In the future they will have throttling/offline modes to simulate bad or non-existent connections, which will be a really good thing.

- -

Firefox has also started to implement some useful tools related to service workers:

- - - -

Spesifikasi

- - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('Service Workers', '')}}{{Spec2('Service Workers')}}Initial definition.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("33.0") }}[1]{{CompatNo}}24{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}{{CompatChrome(40.0)}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown() }}{{CompatNo}}
-
- -

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

- -

Lihat juga

- - diff --git a/files/id/web/api/serviceworker/index.html b/files/id/web/api/serviceworker/index.html deleted file mode 100644 index 26787c6031..0000000000 --- a/files/id/web/api/serviceworker/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: ServiceWorker -slug: Web/API/ServiceWorker -tags: - - API - - Draft - - Offline - - Referensi - - ServiceWorker -translation_of: Web/API/ServiceWorker ---- -
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
- -

Antarmuka ServiceWorker dari ServiceWorker API menyediakan referensi kepada service worker. Konteks multi browsing (mis. halaman, pekerja, dll.) dapat dikaitkan dengan service worker yang sama, masing - masing melalui objek ServiceWorker tersendiri.

- -

Objek ServiceWorker tersedia di properti {{domxref("ServiceWorkerRegistration.active")}} , dan properti {{domxref("ServiceWorkerContainer.controller")}}  — ini adalah service worker yang aktif dan mengontrol halaman (service worker telah sukses terdaftar, dan halaman yang di kontrol telah di muat kembali.)

- -

Antarmuka ServiceWorker terbagi sebagai rangkaian siklus event — install dan activate — dan fungsional event termasuk fetch. Objek ServiceWorker memiliki keterkaitan {{domxref("ServiceWorker.state")}}, berdasarkan siklusnya.

- -

Properti

- -

Antarmuka ServiceWorker mewarisi properti dari induknya, {{domxref("Worker")}}.

- -
-
{{domxref("ServiceWorker.scriptURL")}} {{readonlyinline}}
-
Mengembalikan serialisasi script URL ServiceWorker didefinisikan sebagai bagian dari {{domxref("ServiceWorkerRegistration")}}. URL harus dari origin yang sama dengan dokumen yang mendaftarkan ServiceWorker.
-
{{domxref("ServiceWorker.state")}} {{readonlyinline}}
-
Mengembalikan status keadaan service worker. Akan mengembalikan salah satu dari nilai berikut: installing, installed, activating, activated, atau redundant.
-
- -

Event handlers

- -
-
{{domxref("ServiceWorker.onstatechange")}} {{readonlyinline}}
-
Properti {{domxref("EventListener")}} dipanggil setiap kali event type statechange di jalankan; Pada dasarnya dijalankan setiap ada perubahan pada {{domxref("ServiceWorker.state")}}.
-
- -

Method

- -

Antarmuka ServiceWorker mewarisi method dari induknya, {{domxref("Worker")}}, dengan pengecualian {{domxref("Worker.terminate")}} — tidak harus dapat diakses dari service workers.

- -

Contoh

- -

Ini adalah potongan kode dari service worker registration-events sample (live demo). Kode memperhatikan setiap perubahan di {{domxref("ServiceWorker.state")}} dan mengembalikan nilainya.

- -
if ('serviceWorker' in navigator) {
-    navigator.serviceWorker.register('service-worker.js', {
-        scope: './'
-    }).then(function (registration) {
-        var serviceWorker;
-        if (registration.installing) {
-            serviceWorker = registration.installing;
-            document.querySelector('#kind').textContent = 'Menginstall';
-        } else if (registration.waiting) {
-            serviceWorker = registration.waiting;
-            document.querySelector('#kind').textContent = 'Mengunggu';
-        } else if (registration.active) {
-            serviceWorker = registration.active;
-            document.querySelector('#kind').textContent = 'Aktif';
-        }
-        if (serviceWorker) {
-            // logState(serviceWorker.state);
-            serviceWorker.addEventListener('statechange', function (e) {
-                // logState(e.target.state);
-            });
-        }
-    }).catch (function (error) {
-        // Terjadi kesalahan saat mendaftarkan. File service-worker.js
-        // mungkin tidak tersedia atau terdapat sintaks yang error.
-    });
-} else {
-    // Browser ini tidak mendukung service worker.
-}
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('Service Workers', '#service-worker-obj', 'ServiceWorker')}}{{Spec2('Service Workers')}}Definisi inisial
- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}24{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
-
- -

[1] Service workers (dan Push) telah di nonaktifkan di Firefox 45 Extended Support Release (ESR.)

- -

See also

- - diff --git a/files/id/web/api/serviceworkercontainer/index.html b/files/id/web/api/serviceworkercontainer/index.html deleted file mode 100644 index ab3f71a543..0000000000 --- a/files/id/web/api/serviceworkercontainer/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: ServiceWorkerContainer -slug: Web/API/ServiceWorkerContainer -tags: - - API - - Draft - - Interface - - NeedsTranslation - - Offline - - Reference - - Service Workers - - Service worker API - - ServiceWorkerContainer - - TopicStub - - Workers -translation_of: Web/API/ServiceWorkerContainer ---- -

{{APIRef("Service Workers API")}}

- -

The ServiceWorkerContainer interface of the Service Worker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.

- -

Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}} property used to determine whether or not the current page is actively controlled.

- -

Properties

- -
-
{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}
-
Returns a {{domxref("ServiceWorker")}} object if its state is activated (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns null during a force-refresh request (Shift + refresh) or if there is no active worker.
-
- -
-
{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}
-
Provides a way of delaying code execution until a service worker is active. It returns a {{jsxref("Promise")}} that will never reject, and which waits indefinitely until the {{domxref("ServiceWorkerRegistration")}} associated with the current page has an {{domxref("ServiceWorkerRegistration.active")}} worker. Once that condition is met, it resolves with the {{domxref("ServiceWorkerRegistration")}}.
-
- -

Events

- -
-
controllerchange
-
Occurs when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.
- Also available via the {{domxref("ServiceWorkerContainer.oncontrollerchange")}} property.
-
error
-
Fired whenever an error occurs in the associated service workers.
- Also available via the {{domxref("ServiceWorkerContainer.onerror")}} property.
-
message
-
Occurs when incoming messages are received by the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call.)
- Also available via the {{domxref("ServiceWorkerContainer.onmessage")}} property.
-
- -

Methods

- -
-
{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} 
-
Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given scriptURL.
-
{{domxref("ServiceWorkerContainer.getRegistration()")}}
-
Gets a {{domxref("ServiceWorkerRegistration")}} object whose scope matches the provided document URL.  The method returns a {{jsxref("Promise")}} that resolves to a {{domxref("ServiceWorkerRegistration")}} or undefined
-
{{domxref("ServiceWorkerContainer.getRegistrations()")}}
-
Returns all {{domxref("ServiceWorkerRegistration")}} objects associated with a ServiceWorkerContainer in an array.  The method returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("ServiceWorkerRegistration")}}. 
-
{{domxref("ServiceWorkerContainer.startMessages()")}}
-
explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via {{domxref("Client.postMessage()")}}). This can be used to react to sent messages earlier, even before that page's content has finished loading.
-
- -

Examples

- -

The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.

- -
if ('serviceWorker' in navigator) {
-  // Register a service worker hosted at the root of the
-  // site using the default scope.
-  navigator.serviceWorker.register('/sw.js').then(function(registration) {
-    console.log('Service worker registration succeeded:', registration);
-
-    // At this point, you can optionally do something
-    // with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
-  }).catch(function(error) {
-    console.log('Service worker registration failed:', error);
-  });
-
-  // Independent of the registration, let's also display
-  // information about whether the current page is controlled
-  // by an existing service worker, and when that
-  // controller changes.
-
-  // First, do a one-off check if there's currently a
-  // service worker in control.
-  if (navigator.serviceWorker.controller) {
-    console.log('This page is currently controlled by:', navigator.serviceWorker.controller);
-  }
-
-  // Then, register a handler to detect when a new or
-  // updated service worker takes control.
-  navigator.serviceWorker.oncontrollerchange = function() {
-    console.log('This page is now controlled by:', navigator.serviceWorker.controller);
-  };
-} else {
-  console.log('Service workers are not supported.');
-}
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers', '#serviceworkercontainer', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initial definition.
- -

Browser compatibility

- -
- - -

{{Compat("api.ServiceWorkerContainer")}}

-
- -

See also

- - diff --git a/files/id/web/api/serviceworkerregistration/index.html b/files/id/web/api/serviceworkerregistration/index.html deleted file mode 100644 index 6ce1b3c033..0000000000 --- a/files/id/web/api/serviceworkerregistration/index.html +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: ServiceWorkerRegistration -slug: Web/API/ServiceWorkerRegistration -tags: - - API - - Draft - - Interface - - NeedsTranslation - - Offline - - Reference - - Service Workers - - ServiceWorkerRegistration - - TopicStub - - Workers -translation_of: Web/API/ServiceWorkerRegistration ---- -
-
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
-
- -

The ServiceWorkerRegistration interface of the ServiceWorker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin.

- -

The lifetime of a service worker registration is beyond that of the ServiceWorkerRegistration objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active ServiceWorkerRegistration objects.

- -
-

Note: This feature is available in Web Workers.

-
- -

Properties

- -

Also implements properties from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("ServiceWorkerRegistration.scope")}} {{readonlyinline}}
-
Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}.
-
{{domxref("ServiceWorkerRegistration.installing")}} {{readonlyinline}}
-
Returns a service worker whose state is installing. This is initially set to null.
-
{{domxref("ServiceWorkerRegistration.waiting")}} {{readonlyinline}}
-
Returns a service worker whose state is installed. This is initially set to null.
-
{{domxref("ServiceWorkerRegistration.active")}} {{readonlyinline}}
-
Returns a service worker whose state is either activating or activated. This is initially set to null. An active worker will control a {{domxref("ServiceWorkerClient")}} if the client's URL falls within the scope of the registration (the scope option set when {{domxref("ServiceWorkerContainer.register")}} is first called.)
-
{{domxref("serviceWorkerRegistration.periodicSync")}} {{non-standard_inline}} {{readonlyinline}}
-
Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which manages periodic background synchronization processes.
-
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
-
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.
-
{{domxref("ServiceWorkerRegistration.sync")}} {{non-standard_inline}} {{readonlyinline}} 
-
Returns a reference to the {{domxref("SyncManager")}} interface, which manages background synchronization processes.
-
- -

Event handlers

- -
-
{{domxref("ServiceWorkerRegistration.onupdatefound")}} {{readonlyinline}}
-
An EventListener property called whenever an event of type updatefound is fired; it is fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker.
-
- -

Methods

- -

Also implements methods from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("ServiceWorkerRegistration.getNotifications()")}}
-
Returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("Notification")}} objects.
-
{{domxref("ServiceWorkerRegistration.showNotification()")}}
-
Displays the notification with the requested title.
-
{{domxref("ServiceWorkerRegistration.update()")}}
-
Checks the server for an updated version of the service worker without consulting caches.
-
{{domxref("ServiceWorkerRegistration.unregister()")}}
-
Unregisters the service worker registration and returns a promise (see {{jsxref("Promise")}}). The service worker will finish any ongoing operations before it is unregistered.
-
- -

Examples

- -

This code snippet is from the service worker registration-events sample (live demo). The code checks to see if the browser supports service workers and if there's currently a service worker handling requests on this page for the current navigation.

- -

Any new service workers are registered; if there's an existing service worker, the code overrides its default scope so that the registration applies to the current directory and everything underneath it. The example also reports any registration failures.

- -
if ('serviceWorker' in navigator) {
-  document.querySelector('#availability').innerText = 'are';
-  document.querySelector('#controlled').innerText = navigator.serviceWorker.controller ? 'is' : 'is not';
-  navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function(registration) {
-    document.querySelector('#register').textContent = 'succeeded';
-  }).catch(function(error) {
-    document.querySelector('#register').textContent = 'failed: ' + error;
-  });
-} else {
-  document.querySelector('#availability').innerText = 'are not';
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-obj', 'ServiceWorkerRegistration')}}{{Spec2('Service Workers')}}Initial definition.
{{SpecName('Push API', '#widl-ServiceWorkerRegistration-pushManager', 'PushManager')}}{{Spec2('Push API')}}Adds the {{domxref("PushManager","pushManager")}} property.
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Adds the {{domxref("ServiceWorkerRegistration.showNotification()","showNotification()")}} method and the {{domxref("ServiceWorkerRegistration.getNotifications()","getNotifications()")}} method.
{{SpecName('Background Sync')}}{{Spec2('Background Sync')}}Adds the {{domxref("ServiceWorkerRegistration.sync","sync")}} property.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Available in web workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
getNotifications(), showNotification(){{CompatVersionUnknown}}{{CompatGeckoDesktop("46.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
sync property{{CompatChrome(49.0)}}    
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
Available in web workers{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
getNotifications(), showNotification(){{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("46.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
sync property{{CompatNo}}{{CompatNo}}     {{CompatChrome(49.0)}}
-
- -

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

- -

See also

- - diff --git a/files/id/web/api/serviceworkerregistration/pushmanager/index.html b/files/id/web/api/serviceworkerregistration/pushmanager/index.html deleted file mode 100644 index 57f61c1375..0000000000 --- a/files/id/web/api/serviceworkerregistration/pushmanager/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: ServiceWorkerRegistration.pushManager -slug: Web/API/ServiceWorkerRegistration/pushManager -tags: - - API - - Property - - Push - - PushManager - - ServiceWorker -translation_of: Web/API/ServiceWorkerRegistration/pushManager ---- -
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
- -

Properti pushManager dari interface {{domxref("ServiceWorkerRegistration")}}  Mengembalikan sebuah referensi ke Interface {{domxref("PushManager")}} untuk mengatur push subscriptions; termasuk dukungan untuk berlangganan, mendapatkan langganan yang aktif, dan mengakses izin status push.

- -

Sintaks

- -
myPushManager = ServiceWorker.pushManager
-
- -

Value

- -

Objek {{domxref("PushManager")}}.

- -

Contoh

- -
this.onpush = function(event) {
-  console.log(event.data);
-  // Dari sini kita bisa menyimpan data ke IndexedDB, mengirimnya ke setiap
-  // jendela yang terbuka, menampilkan notifikasi, dsb.
-}
-
-navigator.serviceWorker.register('serviceworker.js').then(
-  function(serviceWorkerRegistration) {
-    serviceWorkerRegistration.pushManager.subscribe().then(
-      function(pushSubscription) {
-        console.log(pushSubscription.subscriptionId);
-        console.log(pushSubscription.endpoint);
-        // Detail langganan push dibutuhkan aplikasi
-        // server kini tersedia, dan dapat di kirimkan menggunakan,
-        // XMLHttpRequest misalnya.
-      }, function(error) {
-        // Pada saat pengembangan menampilkan log ke konsole sangatlah membantu
-        // Di lingkungan produksi juga dapat bermanfaat untuk mengirimkan
-        // informasi error kembali ke aplikasi server.
-        console.log(error);
-      }
-    );
-  });
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Push API', '#pushmanager-interface', 'PushManager')}}{{Spec2('Push API')}}Initial definition.
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
-
- -

[1] Service workers (dan Push) telah dinonaktifkan di Firefox 45 Extended Support Release (ESR.)

- -

Lihat Juga

- - diff --git a/files/id/web/api/speechsynthesis/index.html b/files/id/web/api/speechsynthesis/index.html deleted file mode 100644 index 78a50f3f47..0000000000 --- a/files/id/web/api/speechsynthesis/index.html +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: SpeechSynthesis -slug: Web/API/SpeechSynthesis -tags: - - API - - Experimental - - Interface - - NeedsTranslation - - Reference - - SpeechSynthesis - - TopicStub - - Web Speech API - - speech - - synthesis -translation_of: Web/API/SpeechSynthesis ---- -

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

- -

The SpeechSynthesis interface of the Web Speech API is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.

- -

Properties

- -

SpeechSynthesis also inherits properties from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("SpeechSynthesis.paused")}} {{readonlyinline}}
-
A {{domxref("Boolean")}} that returns true if the SpeechSynthesis object is in a paused state.
-
{{domxref("SpeechSynthesis.pending")}} {{readonlyinline}}
-
A {{domxref("Boolean")}} that returns true if the utterance queue contains as-yet-unspoken utterances.
-
{{domxref("SpeechSynthesis.speaking")}} {{readonlyinline}}
-
A {{domxref("Boolean")}} that returns true if an utterance is currently in the process of being spoken — even if SpeechSynthesis is in a paused state.
-
- -
-
- -

Methods

- -

SpeechSynthesis also inherits methods from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("SpeechSynthesis.cancel()")}}
-
Removes all utterances from the utterance queue.
-
{{domxref("SpeechSynthesis.getVoices()")}}
-
Returns a list of {{domxref("SpeechSynthesisVoice")}} objects representing all the available voices on the current device.
-
{{domxref("SpeechSynthesis.pause()")}}
-
Puts the SpeechSynthesis object into a paused state.
-
{{domxref("SpeechSynthesis.resume()")}}
-
Puts the SpeechSynthesis object into a non-paused state: resumes it if it was already paused.
-
{{domxref("SpeechSynthesis.speak()")}}
-
Adds an {{domxref("SpeechSynthesisUtterance", "utterance")}} to the utterance queue; it will be spoken when any other utterances queued before it have been spoken.
-
- -

Events

- -

Listen to this event using addEventListener() or by assigning an event listener to the oneventname property of this interface.

- -
-
voiceschanged
-
Fired when the list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed.
- Also available via the onvoiceschanged property.
-
- -

Examples

- -

In our basic Speech synthesiser demo, we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. After defining some necessary variables, we retrieve a list of the voices available using {{domxref("SpeechSynthesis.getVoices()")}} and populate a select menu with them so the user can choose what voice they want.

- -

Inside the inputForm.onsubmit handler, we stop the form submitting with preventDefault(),  create a new {{domxref("SpeechSynthesisUtterance")}} instance containing the text from the text {{htmlelement("input")}}, set the utterance's voice to the voice selected in the {{htmlelement("select")}} element, and start the utterance speaking via the {{domxref("SpeechSynthesis.speak()")}} method.

- -
var synth = window.speechSynthesis;
-
-var inputForm = document.querySelector('form');
-var inputTxt = document.querySelector('.txt');
-var voiceSelect = document.querySelector('select');
-
-var pitch = document.querySelector('#pitch');
-var pitchValue = document.querySelector('.pitch-value');
-var rate = document.querySelector('#rate');
-var rateValue = document.querySelector('.rate-value');
-
-var voices = [];
-
-function populateVoiceList() {
-  voices = synth.getVoices();
-
-  for(i = 0; i < voices.length ; i++) {
-    var option = document.createElement('option');
-    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
-
-    if(voices[i].default) {
-      option.textContent += ' -- DEFAULT';
-    }
-
-    option.setAttribute('data-lang', voices[i].lang);
-    option.setAttribute('data-name', voices[i].name);
-    voiceSelect.appendChild(option);
-  }
-}
-
-populateVoiceList();
-if (speechSynthesis.onvoiceschanged !== undefined) {
-  speechSynthesis.onvoiceschanged = populateVoiceList;
-}
-
-inputForm.onsubmit = function(event) {
-  event.preventDefault();
-
-  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
-  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
-  for(i = 0; i < voices.length ; i++) {
-    if(voices[i].name === selectedOption) {
-      utterThis.voice = voices[i];
-    }
-  }
-  utterThis.pitch = pitch.value;
-  utterThis.rate = rate.value;
-  synth.speak(utterThis);
-
-  inputTxt.blur();
-}
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}}{{Spec2('Web Speech API')}} 
- -

Browser compatibility

- -
- - -

{{Compat("api.SpeechSynthesis")}}

-
- -

See also

- - diff --git a/files/id/web/api/speechsynthesis/onvoiceschanged/index.html b/files/id/web/api/speechsynthesis/onvoiceschanged/index.html deleted file mode 100644 index 3a5a3f799c..0000000000 --- a/files/id/web/api/speechsynthesis/onvoiceschanged/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: Kk -slug: Web/API/SpeechSynthesis/onvoiceschanged -translation_of: Web/API/SpeechSynthesis/onvoiceschanged ---- -
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
- -

The onvoiceschanged property of the {{domxref("SpeechSynthesis")}} interface represents an event handler that will run when the list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the voiceschanged event fires.)

- -

This may occur when speech synthesis is being done on the server-side and the voices list is being determined asynchronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running.

- -

Syntax

- -
speechSynthesisInstance.onvoiceschanged = function() { ... };
-
- -

Examples

- -

This could be used to populate a list of voices that the user can choose between when the event fires (see our Speak easy synthesis demo.) Note that Firefox doesn't support it at present, and will just return a list of voices when {{domxref("SpeechSynthesis.getVoices()")}} is fired. With Chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below.

- -
var voices = [];
-
-function populateVoiceList() {
-  voices = synth.getVoices();
-
-  for(i = 0; i < voices.length ; i++) {
-    var option = document.createElement('option');
-    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
-
-    if(voices[i].default) {
-      option.textContent += ' -- DEFAULT';
-    }
-
-    option.setAttribute('data-lang', voices[i].lang);
-    option.setAttribute('data-name', voices[i].name);
-    voiceSelect.appendChild(option);
-  }
-}
-
-populateVoiceList();
-if (speechSynthesis.onvoiceschanged !== undefined) {
-  speechSynthesis.onvoiceschanged = populateVoiceList;
-}
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Speech API', '#dom-speechsynthesis-onvoiceschanged', 'onvoiceschanged')}}{{Spec2('Web Speech API')}}
- -

Browser compatibility

- -
- - -

{{Compat("api.SpeechSynthesis.onvoiceschanged")}}

-
- -

See also

- - diff --git a/files/id/web/api/storage/index.html b/files/id/web/api/storage/index.html deleted file mode 100644 index 2231fe2bd8..0000000000 --- a/files/id/web/api/storage/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Storage -slug: Web/API/Storage -translation_of: Web/API/Storage ---- -
{{APIRef("Web Storage API")}}
- -

The Storage interface of the Web Storage API provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.

- -

To manipulate, for instance, the session storage for a domain, a call to {{domxref("Window.sessionStorage")}} is made; whereas for local storage the call is made to {{domxref("Window.localStorage")}}.

- -

Properties

- -
-
{{domxref("Storage.length")}} {{readonlyInline}}
-
Returns an integer representing the number of data items stored in the Storage object.
-
- -

Methods

- -
-
{{domxref("Storage.key()")}}
-
When passed a number n, this method will return the name of the nth key in the storage.
-
- -
-
{{domxref("Storage.getItem()")}}
-
When passed a key name, will return that key's value.
-
{{domxref("Storage.setItem()")}}
-
When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.
-
{{domxref("Storage.removeItem()")}}
-
When passed a key name, will remove that key from the storage.
-
{{domxref("Storage.clear()")}}
-
When invoked, will empty all keys out of the storage.
-
- -

Examples

- -

Here we access a Storage object by calling localStorage. We first test whether the local storage contains data items using !localStorage.getItem('bgcolor'). If it does, we run a function called setStyles() that grabs the data items using {{domxref("Storage.getItem()")}} and uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses {{domxref("Storage.setItem()")}} to set the item values, then runs setStyles().

- -
if(!localStorage.getItem('bgcolor')) {
-  populateStorage();
-}
-setStyles();
-
-function populateStorage() {
-  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
-  localStorage.setItem('font', document.getElementById('font').value);
-  localStorage.setItem('image', document.getElementById('image').value);
-}
-
-function setStyles() {
-  var currentColor = localStorage.getItem('bgcolor');
-  var currentFont = localStorage.getItem('font');
-  var currentImage = localStorage.getItem('image');
-
-  document.getElementById('bgcolor').value = currentColor;
-  document.getElementById('font').value = currentFont;
-  document.getElementById('image').value = currentImage;
-
-  htmlElem.style.backgroundColor = '#' + currentColor;
-  pElem.style.fontFamily = currentFont;
-  imgElem.setAttribute('src', currentImage);
-}
- -
-

Note: To see this running as a complete working example, see our Web Storage Demo.

-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#the-storage-interface', 'Storage')}}{{Spec2('HTML WHATWG')}} 
- -

Browser compatibility

- - - -

{{Compat("api.Storage")}}

- -

See also

- - diff --git a/files/id/web/api/webgl_api/index.html b/files/id/web/api/webgl_api/index.html deleted file mode 100644 index 3450359705..0000000000 --- a/files/id/web/api/webgl_api/index.html +++ /dev/null @@ -1,235 +0,0 @@ ---- -title: WebGL -slug: Web/API/WebGL_API -tags: - - Referensi - - WebGL -translation_of: Web/API/WebGL_API ---- -
{{WebGLSidebar}}
- -
-

WebGL (Web Graphics Library) merupakan JavaScript API untuk merender grafik interaktif dalam bentuk 3D dan 2D pada setiap web browser yang kompitable tanpa menggunakan plug-in. WebGL juga memperkenalkan sebuah API yang berkaitan erat dengan OpenGL ES 2.0 yang dapat digunakan di elemen {{HTMLElement("canvas")}} HTML5.

-
- -

Dukungan WebGL telah tersedia di Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ dan Internet Explorer 11+; namum, perangkat pengguna juga harus memiliki perangkat keras yang mendukung fitur ini.

- -

Elemen {{HTMLElement("canvas")}} juga digunakan oleh Canvas 2D untuk menggambar grafik 2D pada halaman web.

- -

Referensi

- -

Standar Antarmuka

- -
- -
- -

Ekstensi

- -
- -
- -

Event

- - - -

Tipe dan konstanta

- - - -

Paduan dan tutorial

- - - -

Tutorial lanjutan

- - - -

Sumber

- - - -

Pustaka

- - - -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Initial definition. Based on OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Builds on top of WebGL1. Based on OpenGL ES 3.0.
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}} 
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2.0")}}91112[1]5.1[1]
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)Chrome for AndroidIE MobileOpera MobileSafari Mobile
Basic support425[1]{{CompatNo}}12[1]8.1
-
- -

[1]  Implementasi dari fitur ini adalah eksperimental.

- -

Catatan kompabilitas

- -

Selain browser, GPU sendiri juga dibutuhkan untuk mendukung fitur ini. Contohnya, S3 Texture Compression (S3TC) hanya tersedia di tablet berbasis Tegra. Hampir setiap browser membuat konteks WebGL tersedia dari nama konteks webgl, tapi untuk yang lebih lama juga memerlukan experimental-webgl. Selain itu , nantinya WebGL 2 sepenuhnya kompitable dengan yang sebelumnya dan akan memiliki nama konteks webgl2.

- -

Catatan Gecko

- -

Pengujian dan debungging WebGL

- -

Dimulai dari Gecko 10.0 {{geckoRelease("10.0")}}, disana tersedia dua pengaturan yang memungkinkan anda mengontrol kemampuan WebGL untuk keperluan percobaan:

- -
-
webgl.min_capability_mode
-
Properti Boolean yang, jika true, mengaktifkan mode kemampuan minimum. Pada mode ini, WebGL hanya diatur untuk mendukung fitur pengaturan minimum dan kemampuan yang dibutuhkan oleh spesifikasi WebGL. Memungkinkan anda untuk memastikan bahwa kode WebGL anda akan bekerja untuk setiap perangkat atau browser, tergantung dari kemampuan mereka. Nilai defaultnya adalah false.
-
webgl.disable_extensions
-
Properti Boolean yang, jika true, menonaktifkan semua ekstensi WebGL. Nilai defaultnya false.
-
- -

Lihat Juga

- - diff --git a/files/id/web/api/webrtc_api/index.html b/files/id/web/api/webrtc_api/index.html deleted file mode 100644 index 6d9aa7392c..0000000000 --- a/files/id/web/api/webrtc_api/index.html +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: WebRTC API -slug: Web/API/WebRTC_API -translation_of: Web/API/WebRTC_API ---- -
{{APIRef("WebRTC")}}
- -

WebRTC (Web Real-Time Communications) merupakan teknologi yang memungkinkan situs dan aplikasi berbasis web menangkap dan mengirimkan audio atau video, serta bertukar data antar peramban web tanpa memerlukan adanya perantara. Kumpulan standar di dalam WebRTC membuat pertukaran data dan telekonferensi secara peer-to-peer dapat terjadi tanpa perlu memasang plugins atau aplikasi pihak ketiga.

- -

WebRTC terdiri dari berbagai API dan protokol yang saling terkait sehingga dapat bekerja sebagaimana mestinya. Dokumentasi ini akan membantu anda untuk memahami dasar-dasar WebRTC, bagaimana mengatur dan menggunakan sambungan data dan media, serta hal lainnya.

- -

Konsep dan cara penggunaan WebRTC

- -

WebRTC memiliki beberapa fungsi, begitu halnya juga dengan Media Capture and Streams ({{domxref("MediaDevices")}}) API. Keduanya menghadirkan kemampuan multimedia di dalam web, misalnya audio dan video conferencing, pertukaran file, identity management, serta interaksi pada jaringan telepon dengan cara mengirimkan sinyal {{Glossary("DTMF")}}. Sambungan antar peer dapat terbentuk tanpa plugins tambahan, dan sering kali dapat terbentuk tanpa memerlukan server perantara.

- -

Sambungan antar peer dibuat menggunakan - dan direpresentasikan oleh - {{domxref("RTCPeerConnection")}}. Ketika sebuah sambungan telah terbentuk dan terbuka, stream media ({{domxref("MediaStream")}}) atau channel data ({{domxref("RTCDataChannel")}}) dapat ditambahkan ke dalam sambungan peer.

- -

Stream media terdiri dari beberapa track media, yang direpresentasikan oleh sebuah objek {{domxref("MediaStreamTrack")}}, yang berisi salah satu tipe media, yaitu audio, video, dan teks (misalnya subtitle atau nama judul). Umumnya stream terdiri dari setidaknya satu track audio bahkan juga satu track video, dan dapat digunakan untuk mengirim dan menerima media secara live atau dapat berupa rekaman media (misalnya streaming film).

- -

Anda juga dapat menggunakan sambungan antar peer untuk bertukar sembarang data biner menggunakan {{domxref("RTCDataChannel")}}. Sambungan ini dapat digunakan untuk informasi back-channel, metadatagamingfile transfer, bahkan sebagai jalur utama pertukaran data.

- -

artikel ini memerlukan informasi yang lebih lanjut serta tautan untuk panduan dan tutorial yang relevan

- -

WebRTC interfaces

- -

Because WebRTC provides interfaces that work together to accomplish a variety of tasks, we have divided up the interfaces in the list below by category. Please see the sidebar for an alphabetical list.

- -

Connection setup and management

- -

These interfaces are used to set up, open, and manage WebRTC connections.

- -
-
{{domxref("RTCPeerConnection")}}
-
Represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.
-
{{domxref("RTCDataChannel")}}
-
Represents a bi-directional data channel between two peers of a connection.
-
{{domxref("RTCDataChannelEvent")}}
-
Represents events that occur while attaching a {{domxref("RTCDataChannel")}} to a {{domxref("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.
-
{{domxref("RTCSessionDescription")}}
-
Represents the parameters of a session. Each RTCSessionDescription consists of a description type indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session.
-
{{domxref("RTCStatsReport")}}
-
Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling {{domxref("RTCPeerConnection.getStats()")}}.
-
{{domxref("RTCIceCandidate")}}
-
Represents a candidate internet connectivity establishment (ICE) server for establishing an {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCIceTransport")}}
-
Represents information about an internet connectivity establishment (ICE) transport.
-
{{domxref("RTCPeerConnectionIceEvent")}}
-
Represents events that occurs in relation to ICE candidates with the target, usually an {{domxref("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.
-
{{domxref("RTCRtpSender")}}
-
Manages the encoding and transmission of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCRtpReceiver")}}
-
Manages the reception and decoding of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCTrackEvent")}}
-
Indicates that a new incoming {{domxref("MediaStreamTrack")}} was created and an associated {{domxref("RTCRtpReceiver")}} object was added to the {{domxref("RTCPeerConnection")}} object.
-
- -

Identity and security

- -

The WebRTC API includes a number of interfaces to manage security and identity.

- -
-
{{domxref("RTCIdentityProvider")}}
-
Enables a user agent is able to request that an identity assertion be generated or validated.
-
{{domxref("RTCIdentityAssertion")}}
-
Represents the identity of the a remote peer of the current connection. If no peer has yet been set and verified this interface returns null. Once set it can't be changed.
-
{{domxref("RTCIdentityProviderRegistrar")}}
-
Registers an  identity provider (idP).
-
{{domxref("RTCIdentityEvent")}}
-
Represents an identity assertion generated by an identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. The only event sent with this type is {{event("identityresult")}}.
-
{{domxref("RTCIdentityErrorEvent")}}
-
Represents an error associated with the identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. Two events are sent with this type: {{event("idpassertionerror")}} and {{event("idpvalidationerror")}}.
-
{{domxref("RTCCertificate")}}
-
Represents a certificate that an {{domxref("RTCPeerConnection")}} uses to authenticate.
-
- -

Telephony

- -

These interfaces are related to interactivity with public-switched telephone networks (PTSNs).

- -
-
{{domxref("RTCDTMFSender")}}
-
Manages the encoding and transmission of dual-tone multi-frequency (DTMF) signaling for an {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCDTMFToneChangeEvent")}}
-
Indicates an occurrence of a of dual-tone multi-frequency (DTMF). This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).
-
- -

Guides

- -
-
Introduction to WebRTC protocols
-
This article introduces the protocols on top of which the WebRTC API is built.
-
WebRTC connectivity
-
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
-
Lifetime of a WebRTC session
-
WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.
-
Signaling and two-way video calling
-
A tutorial and example which turbs a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.
-
Using WebRTC data channels
-
This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.
-
Using DTMF with WebRTC
-
WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{domxref("RTCDTMFSender")}} interface. This guide shows how to do so.
-
- -

Tutorials

- -
-
Improving compatibility using WebRTC adapter.js
-
The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.
-
Taking still photos with WebRTC
-
This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.
-
A simple RTCDataChannel sample
-
The {{domxref("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be used for each.
-
- -

Resources

- -

Protocols

- -

WebRTC-proper protocols

- - - - - - - -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}The initial definition of the API of WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}The initial definition of the object conveying the stream of media content.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}The initial definition on how to obtain stream of content from DOM Elements
- -

In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under resources.

- - - - diff --git a/files/id/web/api/window/getselection/index.html b/files/id/web/api/window/getselection/index.html deleted file mode 100644 index 274aa85b2d..0000000000 --- a/files/id/web/api/window/getselection/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Window.getSelection() -slug: Web/API/Window/getSelection -tags: - - API - - API Pilihan - - DOM - - Metode - - Pilihan - - Refrensi - - Window -translation_of: Web/API/Window/getSelection ---- -
{{ ApiRef() }}
- -

Window.getSelection() adalah metode {{domxref("Selection")}} yang menggambarkan teks yang ditandai oleh pengguna atau posisi sekarang.

- -

Syntak

- -
selection = window.getSelection();
- -

Hasil Output

- -

Objek {{domxref("Selection")}}

- -

Ketika berganti ke string, lebih baik menggunakan string kosong ("") atau menggunakan {{domxref("Selection.toString()")}}, hasil output adalah teks yang dipilih.

- -

Ketika memanggil sebuah {{htmlelement("iframe")}} ini tidak akan ditampilkan (misalnya display: none telah diatur) Firefox akan menampilkan null, sedangkan browser lain akan menampilkan objek {{domxref("Selection")}} dengan {{domxref("Selection.type")}} yang diatur ke None.

- -

Contoh

- -
function foo() {
-    var selObj = window.getSelection();
-    alert(selObj);
-    var selRange = selObj.getRangeAt(0);
-    // do stuff with the range
-}
- -

Catatan

- -

Representasi dari objek Selection

- -

Dalam JavaScript, ketika sebuah objek dimasukan ke function yang membutuhkan string (seperti {{ Domxref("window.alert()") }} atau {{ Domxref("document.write()") }}), objek metode {{jsxref("Object.toString", "toString()")}} akan dipanggil dan hasilnya akan dikembalikan ke function tersebut. Ini akan membuat objek dapat tampil sebagai string ketika digunakan oleh function lainnya ketika ini adalah objek dan metode yang benar.

- -

Pada contoh berikut, selObj.toString() akan otomatis dipanggil ketika melewati {{domxref("window.alert()")}}. Bagaimanapun, mencoba menggunakan properti atau metode JavaScript String seperti length atau substr secara langsung pada objek {{domxref ("Selection")}} akan menghasilkan kesalahan jika tidak memiliki properti atau metode dan dapat mengembalikan hasil yang tidak terduga jika itu benar. Untuk menggunakan objek Selection sebagai string, panggil metode toString () secara langsung:

- -
var selectedText = selObj.toString();
- - - -

Objek terhubung

- -

Kamu bisa memanggil {{domxref("Document.getSelection()")}}, yang mana ini bekerja seperti Window.getSelection().

- -

Perlu diingat, bahwa saat ini getSelection() tidak bekerja pada elemen {{htmlelement("textarea")}} and {{htmlelement("input")}} di Firefox. Properti {{domxref("HTMLInputElement.setSelectionRange()")}} atau selectionStart dan selectionEnd yang dapat menangani hal ini.

- -

Perhatikan juga perbedaan atara selection dan focus. {{domxref("Document.activeElement")}} menampilkan elemen yang sedang difokus.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("Selection API", "#extensions-to-window-interface", "Window.getSelection()")}}{{Spec2("Selection API")}}New spec.
{{SpecName("HTML Editing", "#dom-window-getselection", "Window.getSelection()")}}{{Spec2("HTML Editing")}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("api.Window.getSelection")}}

- -

See also

- - diff --git a/files/id/web/api/window/index.html b/files/id/web/api/window/index.html deleted file mode 100644 index 9dc063344a..0000000000 --- a/files/id/web/api/window/index.html +++ /dev/null @@ -1,479 +0,0 @@ ---- -title: Window -slug: Web/API/Window -tags: - - API - - DOM - - Interface - - JavaScript - - NeedsTranslation - - Reference - - TopicStub - - Window -translation_of: Web/API/Window ---- -

{{APIRef}}

- -

The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the {{Domxref("document.defaultView")}} property.

- -

This section provides a brief reference for all of the methods, properties, and events available through the DOM window object. The window object implements the Window interface, which in turn inherits from the AbstractView interface. Some additional global functions, namespaces, objects, interfaces, and constructors, not typically associated with the window, but available on it, are listed in the JavaScript Reference and DOM Reference.

- -

In a tabbed browser, such as Firefox, each tab contains its own window object (and if you're writing an extension, the browser window itself is a separate window too - see Working with windows in chrome code for more information). That is, the window object is not shared between tabs in the same window. Some methods, namely {{Domxref("window.resizeTo")}} and {{Domxref("window.resizeBy")}} apply to the whole window and not to the specific tab the window object belongs to. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

- -

{{InheritanceDiagram}}

- -

Properties

- -

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.

- -

Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.

- -
-
{{domxref("Window.applicationCache")}}  {{readOnlyInline}} {{gecko_minversion_inline("1.9")}}
-
An {{domxref("OfflineResourceList")}} object providing access to the offline resources for the window.
-
{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}
-
This property indicates whether the current window is closed or not.
-
{{domxref("Window.console")}} {{ReadOnlyInline}}
-
Returns a reference to the console object which provides access to the browser's debugging console.
-
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
-
Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.
-
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
-
Returns the XUL controller objects for the current chrome window.
-
{{domxref("Window.crypto")}} {{readOnlyInline}}
-
Returns the browser crypto object.
-
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
-
Gets/sets the status bar text for the given window.
-
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}
-
Returns the ratio between physical pixels and device independent pixels in the current display.
-
{{domxref("Window.dialogArguments")}} {{ReadOnlyInline}}
-
Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.
-
{{domxref("Window.directories")}} {{obsolete_inline}}
-
Synonym of {{domxref("window.personalbar")}}
-
{{domxref("Window.document")}} {{ReadOnlyInline}}
-
Returns a reference to the document that the window contains.
-
{{domxref("Window.frameElement")}} {{readOnlyInline}}
-
Returns the element in which the window is embedded, or null if the window is not embedded.
-
{{domxref("Window.frames")}} {{readOnlyInline}}
-
Returns an array of the subframes in the current window.
-
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
-
This property indicates whether the window is displayed in full screen or not.
-
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
-
Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.
- Was: Multiple storage objects that are used for storing data across multiple pages.
-
{{domxref("Window.history")}} {{ReadOnlyInline}}
-
Returns a reference to the history object.
-
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
-
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
-
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
-
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
-
{{domxref("Window.isSecureContext")}} {{readOnlyInline}}
-
Indicates whether a context is capable of using features that require secure contexts.
-
{{domxref("Window.length")}} {{readOnlyInline}}
-
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
-
{{domxref("Window.location")}}
-
Gets/sets the location, or current URL, of the window object.
-
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
-
Returns the locationbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
-
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
-
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
-
Returns the menubar object, whose visibility can be toggled in the window.
-
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
-
Returns the message manager object for this window.
-
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
-
The time in milliseconds since epoch at which the current animation cycle began.
-
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
-
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
-
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
-
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
-
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
-
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
-
{{domxref("Window.name")}}
-
Gets/sets the name of the window.
-
{{domxref("Window.navigator")}} {{readOnlyInline}}
-
Returns a reference to the navigator object.
-
{{domxref("Window.opener")}}
-
Returns a reference to the window that opened this current window.
-
{{domxref("Window.orientation")}}{{non-standard_inline}}{{deprecated_inline}}{{readOnlyInline}}
-
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
-
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
-
Gets the height of the outside of the browser window.
-
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
-
Gets the width of the outside of the browser window.
-
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
-
An alias for {{domxref("window.scrollX")}}.
-
{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}
-
An alias for {{domxref("window.scrollY")}}
-
{{domxref("Window.sessionStorage")}} {{readOnlyInline}}
-
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
-
{{domxref("Window.parent")}} {{readOnlyInline}}
-
Returns a reference to the parent of the current window or subframe.
-
{{domxref("Window.performance")}} {{readOnlyInline}}
-
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
-
{{domxref("Window.personalbar")}} {{readOnlyInline}}
-
Returns the personalbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
-
Formerly provided access to install and remove PKCS11 modules.
-
{{domxref("Window.returnValue")}}
-
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
-
{{domxref("Window.screen")}} {{readOnlyInline}}
-
Returns a reference to the screen object associated with the window.
- -
{{domxref("Window.screenX")}} {{readOnlyInline}}
-
Returns the horizontal distance of the left border of the user's browser from the left side of the screen.
-
{{domxref("Window.screenY")}} {{readOnlyInline}}
-
Returns the vertical distance of the top border of the user's browser from the top side of the screen.
-
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
-
Returns the scrollbars object, whose visibility can be toggled in the window.
-
{{domxref("Window.scrollMaxX")}}{{non-standard_inline}}{{ReadOnlyInline}}
-
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
-
{{domxref("Window.scrollMaxY")}}{{non-standard_inline}}{{ReadOnlyInline}}
-
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
-
{{domxref("Window.scrollX")}} {{readOnlyInline}}
-
Returns the number of pixels that the document has already been scrolled horizontally.
-
{{domxref("Window.scrollY")}} {{readOnlyInline}}
-
Returns the number of pixels that the document has already been scrolled vertically.
-
{{domxref("Window.self")}} {{ReadOnlyInline}}
-
Returns an object reference to the window object itself.
-
{{domxref("Window.sessionStorage")}}
-
Returns a storage object for storing data within a single page session.
-
{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}
-
Returns a reference to the window object of the sidebar.
-
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
-
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
-
{{domxref("Window.status")}}
-
Gets/sets the text in the statusbar at the bottom of the browser.
-
{{domxref("Window.statusbar")}} {{readOnlyInline}}
-
Returns the statusbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.toolbar")}} {{readOnlyInline}}
-
Returns the toolbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.top")}} {{readOnlyInline}}
-
Returns a reference to the topmost window in the window hierarchy. This property is read only.
-
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
-
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
-
{{domxref("Window.window")}} {{ReadOnlyInline}}
-
Returns a reference to the current window.
-
window[0], window[1], etc.
-
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
-
- -

Properties implemented from elsewhere

- -
-
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
-
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
-
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
-
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
-
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
-
Returns a boolean indicating whether the current context is secure (true) or not (false).
-
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
-
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
-
- -

Methods

- -

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.

- -
-
{{domxref("Window.alert()")}}
-
Displays an alert dialog.
- -
{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Moves back one in the window history.
-
{{domxref("Window.blur()")}}
-
Sets focus away from the window.
-
{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}
-
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.
-
{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}
-
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.
-
{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}
-
Registers the window to capture all events of the specified type.
-
{{domxref("Window.clearImmediate()")}}
-
Cancels the repeated execution set using setImmediate.
-
{{domxref("Window.close()")}}
-
Closes the current window.
-
{{domxref("Window.confirm()")}}
-
Displays a dialog with a message that the user needs to respond to.
-
{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.dispatchEvent()")}}
-
Used to trigger an event.
-
{{domxref("Window.dump()")}} {{Non-standard_inline}}
-
Writes a message to the console.
-
{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.find()")}}
-
Searches for a given string in a window.
-
{{domxref("Window.focus()")}}
-
Sets focus on the current window.
-
{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Moves the window one document forward in the history.
-
{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Flashes the application icon.
-
{{domxref("Window.getAttentionWithCycleCount()")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.getComputedStyle()")}}
-
Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
-
{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}
-
Gets default computed style for the specified element, ignoring author stylesheets.
-
{{domxref("Window.getSelection()")}}
-
Returns the selection object representing the selected item(s).
-
{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Returns the browser to the home page.
-
{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}
-
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
-
{{domxref("Window.maximize()")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.minimize()")}} (top-level XUL windows only)
-
Minimizes the window.
-
{{domxref("Window.moveBy()")}}
-
Moves the current window by a specified amount.
-
{{domxref("Window.moveTo()")}}
-
Moves the window to the specified coordinates.
-
{{domxref("Window.open()")}}
-
Opens a new window.
-
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Opens a new dialog window.
-
{{domxref("Window.postMessage()")}}
-
Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.
-
{{domxref("Window.print()")}}
-
Opens the Print Dialog to print the current document.
-
{{domxref("Window.prompt()")}}
-
Returns the text entered by the user in a prompt dialog.
-
{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}
-
Releases the window from trapping events of a specific type.
-
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
-
Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
-
{{domxref("Window.requestIdleCallback()")}}  {{experimental_inline}}
-
Enables the scheduling of tasks during a browser's idle periods.
-
{{domxref("Window.resizeBy()")}}
-
Resizes the current window by a certain amount.
-
{{domxref("Window.resizeTo()")}}
-
Dynamically resizes window.
-
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.scroll()")}}
-
Scrolls the window to a particular place in the document.
-
{{domxref("Window.scrollBy()")}}
-
Scrolls the document in the window by the given amount.
-
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
-
Scrolls the document by the given number of lines.
-
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
-
Scrolls the current document by the specified number of pages.
-
{{domxref("Window.scrollTo()")}}
-
Scrolls to a particular set of coordinates in the document.
-
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
-
Changes the cursor for the current window
-
{{domxref("Window.setImmediate()")}}
-
Executes a function after the browser has finished other heavy tasks
-
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
-
Toggles a user's ability to resize a window.
-
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
-
Sizes the window according to its content.
-
{{domxref("Window.stop()")}}
-
This method stops window loading.
-
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
-
Updates the state of commands of the current chrome window (UI).
-
- -

Methods implemented from elsewhere

- -
-
{{domxref("EventTarget.addEventListener()")}}
-
Register an event handler to a specific event type on the window.
-
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
-
Decodes a string of data which has been encoded using base-64 encoding.
-
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
-
Creates a base-64 encoded ASCII string from a string of binary data.
-
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
-
Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.
-
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
-
Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.
-
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
-
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh.
-
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
-
Starts the process of fetching a resource from the network.
-
{{domxref("EventTarget.removeEventListener")}}
-
Removes an event listener from the window.
-
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
-
Schedules a function to execute every time a given number of milliseconds elapses.
-
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
-
Schedules a function to execute in a given amount of time.
-
- -

Obsolete methods

- -
-
{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}
-
Displays a modal dialog. This method was removed completely in Chrome 43, and Firefox 55.
-
- -

Event handlers

- -

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

- -

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.

- -
-

Note: Starting in {{Gecko("9.0")}}, you can now use the syntax if ("onabort" in window) to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See DOM event handlers for details.

-
- -
-
{{domxref("GlobalEventHandlers.onabort")}}
-
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
-
{{domxref("WindowEventHandlers.onafterprint")}}
-
Called when the print dialog box is closed. See {{event("afterprint")}} event.
-
{{domxref("WindowEventHandlers.onbeforeprint")}}
-
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
-
{{domxref("Window.onbeforeinstallprompt")}}
-
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
-
{{domxref("WindowEventHandlers.onbeforeunload")}}
-
An event handler property for before-unload events on the window.
-
{{domxref("GlobalEventHandlers.onblur")}}
-
Called after the window loses focus, such as due to a popup.
-
{{domxref("GlobalEventHandlers.onchange")}}
-
An event handler property for change events on the window.
-
{{domxref("GlobalEventHandlers.onclick")}}
-
Called after the ANY mouse button is pressed & released
-
{{domxref("GlobalEventHandlers.ondblclick")}}
-
Called when a double click is made with ANY mouse button.
-
{{domxref("GlobalEventHandlers.onclose")}}
-
Called after the window is closed
-
{{domxref("GlobalEventHandlers.oncontextmenu")}}
-
Called when the RIGHT mouse button is pressed
-
{{domxref("Window.ondevicelight")}}
-
An event handler property for any ambient light levels changes
-
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
-
Called if accelerometer detects a change (For mobile devices)
-
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
-
Called when the orientation is changed (For mobile devices)
-
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
-
An event handler property for any device orientation changes.
-
{{domxref("Window.ondeviceproximity")}}
-
An event handler property for device proximity event
-
{{domxref("GlobalEventHandlers.onerror")}}
-
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
-
{{domxref("GlobalEventHandlers.onfocus")}}
-
Called after the window receives or regains focus. See {{event("focus")}} events.
-
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
-
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
-
{{domxref("Window.onappinstalled")}}
-
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
-
{{domxref("Window.ongamepadconnected")}}
-
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
-
{{domxref("Window.ongamepaddisconnected")}}
-
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
-
{{domxref("Window.oninput")}}
-
Called when the value of an <input> element changes
-
{{domxref("GlobalEventHandlers.onkeydown")}}
-
Called when you begin pressing ANY key. See {{event("keydown")}} event.
-
{{domxref("GlobalEventHandlers.onkeypress")}}
-
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
-
{{domxref("GlobalEventHandlers.onkeyup")}}
-
Called when you finish releasing ANY key. See {{event("keyup")}} event.
-
{{domxref("WindowEventHandlers.onlanguagechange")}}
-
An event handler property for {{event("languagechange")}} events on the window.
-
{{domxref("GlobalEventHandlers.onload")}}
-
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
-
{{domxref("WindowEventHandlers.onmessage")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmousedown")}}
-
Called when ANY mouse button is pressed.
-
{{domxref("GlobalEventHandlers.onmousemove")}}
-
Called continously when the mouse is moved inside the window.
-
{{domxref("GlobalEventHandlers.onmouseout")}}
-
Called when the pointer leaves the window.
-
{{domxref("GlobalEventHandlers.onmouseover")}}
-
Called when the pointer enters the window
-
{{domxref("GlobalEventHandlers.onmouseup")}}
-
Called when ANY mouse button is released
-
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
-
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
-
{{domxref("WindowEventHandlers.onoffline")}}
-
Called when network connection is lost. See {{event("offline")}} event.
-
{{domxref("WindowEventHandlers.ononline")}}
-
Called when network connection is established. See {{event("online")}} event.
-
{{domxref("WindowEventHandlers.onpagehide")}}
-
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
-
{{domxref("WindowEventHandlers.onpageshow")}}
-
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
-
{{domxref("Window.onpaint")}}
-
An event handler property for paint events on the window.
-
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
-
Called when a back putton is pressed.
-
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
-
An event handler for handled {{jsxref("Promise")}} rejection events.
-
{{domxref("GlobalEventHandlers.onreset")}}
-
Called when a form is reset
-
{{domxref("GlobalEventHandlers.onresize")}}
-
Called continuously as you are resizing the window.
-
{{domxref("GlobalEventHandlers.onscroll")}}
-
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
-
{{domxref("GlobalEventHandlers.onwheel")}}
-
Called when the mouse wheel is rotated around any axis
-
{{domxref("GlobalEventHandlers.onselect")}}
-
Called after text in an input field is selected
-
{{domxref("GlobalEventHandlers.onselectionchange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
-
{{domxref("WindowEventHandlers.onstorage")}}
-
Called when there is a change in session storage or local storage. See {{event("storage")}} event
-
{{domxref("GlobalEventHandlers.onsubmit")}}
-
Called when a form is submitted
-
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
-
An event handler for unhandled {{jsxref("Promise")}} rejection events.
-
{{domxref("WindowEventHandlers.onunload")}}
-
Called when the user navigates away from the page.
-
{{domxref("Window.onuserproximity")}}
-
An event handler property for user proximity events.
-
{{domxref("Window.onvrdisplayconnect")}}
-
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
-
{{domxref("Window.onvrdisplaydisconnect")}}
-
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
-
{{domxref("Window.onvrdisplayactivate")}}
-
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
-
{{domxref("Window.onvrdisplaydeactivate")}}
-
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
-
{{domxref("Window.onvrdisplayblur")}}
-
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
-
{{domxref("Window.onvrdisplayfocus")}}
-
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
-
{{domxref("Window.onvrdisplaypresentchange")}}
-
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
-
- -

Constructors

- -

See also the DOM Interfaces.

- -
-
{{domxref("DOMParser")}}
-
DOMParser can parse XML or HTML source stored in a string into a DOM DocumentDOMParser is specified in DOM Parsing and Serialization.
-
{{domxref("Window.GeckoActiveXObject")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Image")}}
-
Used for creating an {{domxref("HTMLImageElement")}}.
-
{{domxref("Option")}}
-
Used for creating an {{domxref("HTMLOptionElement")}}
-
{{domxref("Window.QueryInterface")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.XMLSerializer")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Worker")}}
-
Used for creating a Web worker
-
{{domxref("Window.XPCNativeWrapper")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.XPCSafeJSObjectWrapper")}}
-
{{todo("NeedsContents")}}
-
- -

Interfaces

- -

See DOM Reference

- -

See also

- - diff --git a/files/id/web/api/window/window/index.html b/files/id/web/api/window/window/index.html deleted file mode 100644 index a40d33059f..0000000000 --- a/files/id/web/api/window/window/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Window.window -slug: Web/API/Window/window -translation_of: Web/API/Window/window ---- -
{{APIRef}}
- -

Summary

- -

Properti window dalam obyek window mengarah pada obyek window itu sendiri. Jadi ekspresi berikut mengembalikan obyek window yang sama:

- -
window.window
-window.window.window
-window.window.window.window
-  ...
-
- -

Pada halaman web, obyek window merupakan obyek global. Ini berarti:

- -
    -
  1. variabel global pada skrip adalah properti dari window: - -
    var global = {data: 0};
    -alert(global === window.global); // displays "true"
    -
    -
  2. -
  3. kamu dapat mengakses properti bawaan dari window tanpa perlu menulis prefix window.: -
    setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout.
    -alert(window === window.window); // displays "true"
    -
    -
  4. -
- -

Tujuan adanya properti window yang mengarah pada obyek itu sendiri adalah mempermudah dalam mengarah pada obyek global. Jika tidak, kamu harus melakukannya secara manual var window = this; dibagian awal skrip.

- -

Alasan lain, ada beberapa hal yang tidak dapat kamu tulis, contohnya, "{{domxref("window.open","window.open('http://google.com/')")}}". kamu harus menulis "open('http://google.com/')".

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-window', 'Window.window')}}{{Spec2('HTML WHATWG')}}No difference from the latest snapshot {{SpecName("HTML5.1")}}
{{SpecName('HTML5.1', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5.1')}}No difference from the {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5 W3C')}}First snapshot containing the definition of Window.window.
diff --git a/files/id/web/api/xmlhttprequest/index.html b/files/id/web/api/xmlhttprequest/index.html deleted file mode 100644 index 87f02b9550..0000000000 --- a/files/id/web/api/xmlhttprequest/index.html +++ /dev/null @@ -1,200 +0,0 @@ ---- -title: XMLHttpRequest -slug: Web/API/XMLHttpRequest -tags: - - AJAX - - API - - Communication - - HTTP - - Interface - - NeedsTranslation - - Reference - - TopicStub - - Web - - XHR - - XMLHttpRequest -translation_of: Web/API/XMLHttpRequest ---- -
{{DefaultAPISidebar("XMLHttpRequest")}}
- -

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in {{Glossary("AJAX")}} programming.

- -

{{InheritanceDiagram(650, 150)}}

- -

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.

- -

If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the {{domxref("EventSource")}} interface. For full-duplex communication, WebSockets may be a better choice.

- -

Constructor

- -
-
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
-
The constructor initializes an XMLHttpRequest. It must be called before any other method calls.
-
- -

Properties

- -

This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.

- -
-
{{domxref("XMLHttpRequest.onreadystatechange")}}
-
An {{domxref("EventHandler")}} that is called whenever the readyState attribute changes.
-
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
-
Returns an unsigned short, the state of the request.
-
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
-
Returns an {{jsxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript object, or a {{domxref("DOMString")}}, depending on the value of {{domxref("XMLHttpRequest.responseType")}}, that contains the response entity body.
-
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
-
Returns a {{domxref("DOMString")}} that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
-
{{domxref("XMLHttpRequest.responseType")}}
-
Is an enumerated value that defines the response type.
-
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
-
Returns the serialized URL of the response or the empty string if the URL is null.
-
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
-
Returns a {{domxref("Document")}} containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.
-
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
-
Returns an unsigned short with the status of the response of the request.
-
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
-
Returns a {{domxref("DOMString")}} containing the response string returned by the HTTP server. Unlike {{domxref("XMLHttpRequest.status")}}, this includes the entire text of the response message ("200 OK", for example).
-
- -
-

Note: According to the HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

-
- -
-
{{domxref("XMLHttpRequest.timeout")}}
-
Is an unsigned long representing the number of milliseconds a request can take before automatically being terminated.
-
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
-
Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}
-
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
-
Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.
-
{{domxref("XMLHttpRequest.withCredentials")}}
-
Is a {{domxref("Boolean")}} that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers.
-
- -

Non-standard properties

- -
-
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
-
Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.
-
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
-
Is a boolean. If true, the request will be sent without cookie and authentication headers.
-
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
-
Is a boolean. If true, the same origin policy will not be enforced on the request.
-
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
-
Is a boolean. It indicates whether or not the object represents a background service request.
-
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
-
{{jsxref("ArrayBuffer")}}. The response to the request, as a JavaScript typed array.
-
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
-
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead.
-
- -

Event handlers

- -

onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.

- -

Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest.

- -

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard {{domxref("EventTarget.addEventListener", "addEventListener()")}} APIs in addition to setting on* properties to a handler function.

- -

Methods

- -
-
{{domxref("XMLHttpRequest.abort()")}}
-
Aborts the request if it has already been sent.
-
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
-
Returns all the response headers, separated by {{Glossary("CRLF")}}, as a string, or null if no response has been received.
-
{{domxref("XMLHttpRequest.getResponseHeader()")}}
-
Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.
-
{{domxref("XMLHttpRequest.open()")}}
-
Initializes a request.
-
{{domxref("XMLHttpRequest.overrideMimeType()")}}
-
Overrides the MIME type returned by the server.
-
{{domxref("XMLHttpRequest.send()")}}
-
Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.
-
{{domxref("XMLHttpRequest.setRequestHeader()")}}
-
Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().
-
- -

Non-standard methods

- -
-
{{domxref("XMLHttpRequest.init()")}}
-
Initializes the object for use from C++ code.
-
- -
Warning: This method must not be called from JavaScript.
- -
-
{{domxref("XMLHttpRequest.openRequest()")}}
-
Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open() instead. See the documentation for open().
-
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
-
A variant of the send() method that sends binary data.
-
- -

Events

- -
-
{{domxref("XMLHttpRequest/abort_event", "abort")}}
-
Fired when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}} property.
-
{{domxref("XMLHttpRequest/error_event", "error")}}
-
Fired when the request encountered an error.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}} property.
-
{{domxref("XMLHttpRequest/load_event", "load")}}
-
Fired when an {{domxref("XMLHttpRequest")}} transaction completes successfully.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onload", "onload")}} property.
-
{{domxref("XMLHttpRequest/loadend_event", "loadend")}}
-
Fired when a request has completed, whether successfully (after {{domxref("XMLHttpRequest/load_event", "load")}}) or unsuccessfully (after {{domxref("XMLHttpRequest/abort_event", "abort")}} or {{domxref("XMLHttpRequest/error_event", "error")}}).
- Also available via the {{domxref("XMLHttpRequestEventTarget/onloadend", "onloadend")}} property.
-
{{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}
-
Fired when a request has started to load data.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onloadstart", "onloadstart")}} property.
-
{{domxref("XMLHttpRequest/progress_event", "progress")}}
-
Fired periodically when a request receives more data.
- Also available via the {{domxref("XMLHttpRequestEventTarget/onprogress", "onprogress")}} property.
-
{{domxref("XMLHttpRequest/timeout_event", "timeout")}}
-
Fired when progress is terminated due to preset time expiring.
- Also available via the {{domxref("XMLHttpRequestEventTarget/ontimeout", "ontimeout")}} property.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
- -

Browser compatibility

- - - -
{{Compat("api.XMLHttpRequest")}}
- -

See also

- - diff --git a/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html deleted file mode 100644 index 1de088b719..0000000000 --- a/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html +++ /dev/null @@ -1,793 +0,0 @@ ---- -title: Using XMLHttpRequest -slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest -translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest ---- -
{{APIRef("XMLHttpRequest")}}
- -
Dalam panduan ini, kita akan melihat bagaimana cara untuk mengunakan {{domxref("XMLHttpRequest")}}  untuk menyelesaikan permasalahan HTTP request yang dalam penggunaan untuk pertukaran data antara halaman web dan server. Contoh umum dan kasus penggunaan lebih jelas untuk XMLHttpRequest disertakan.
- -
- -
Untuk mengirim HTTP request,  buatlah sebuah object XMLHttpRequest , buka sebuah URL dan kirim request tersebut. setelah transaksi selesai, objek akan berisi informasi yang berguna seperti badan respon dan status HTTP dari hasilnya.
- -
- -
function reqListener () {
-  console.log(this.responseText);
-}
-
-var oReq = new XMLHttpRequest();
-oReq.addEventListener("load", reqListener);
-oReq.open("GET", "http://www.example.org/example.txt");
-oReq.send();
- -

Tipe-Tipe dari Request

- -

Sebuh request yang dihasilkan melalui XMLHttpRequest dapat mengambil data dari salah satu cara, asynchronously or synchronously. Tipe dari request ditentukan onleh opsi async argument (argument ke-tiga) yang telah diset dialam metode {{domxref("XMLHttpRequest.open()")}}. Jika argument tersebut true atau tidak ditentukan. XMLHttpRequest akan diproses secara asynchronous,jika tidak proses akan berjalan secara synchronous. Diskusi detail dan demonstrasi dari kedua cara merequest tersebut dapat ditemukan pada halaman synchronous and asynchronous requests. Jangan gunakan permintaan synchronous di luar Pekerja Web.

- -
Note: Dimulai dari Gecko 30.0 {{ geckoRelease("30.0") }}, permintaan synchronous pada utas utama telah ditinggalkan karena efek negatif terhadap pengalaman pengguna.
- -
Note: fungsi konstruksi XMLHttpRequest tidak terbatas hanya pada dokumen XML. Itu dimulai dengan "XML" karena ketika itu dibuat format utama yang awalnya digunakan untuk Asynchronous Data Exchange adalah XML
- -

Menangani Respons

- -

Ada beberapa jenis atribut respons  ditentukan oleh spesifikasi standar untuk {domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} constructor. Ini memberi tahu klien membuat informasi penting XMLHttpRequest tentang status respons. Beberapa kasus di mana berurusan dengan jenis respons non-teks mungkin melibatkan beberapa manipulasi dan analisis diuraikan dalam bagian berikut.

- -

Menganalisa dan Memanipulasi Properti responseXML

- -

Jika kamu mengunakan XMLHttpRequest  untuk mendapatkan konten dokumen XML jarak jauh, properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}  akan menjadi objek DOM yang berisi dokumen XML parsing. Ini terbentuk sulit untuk dimanipulasi dan dianalisis. Ada empat cara utama untuk menganalisis dokumen XML ini:

- -
    -
  1. Menggunakan XPath untuk mengatasi (atau menunjuk ke) bagian-bagiannya.
  2. -
  3. Secara manual Parsing dan men-serialisasikan XML ke string atau objek
  4. -
  5. Menggunakan {{domxref("XMLSerializer")}} untuk meng-serialisasi Pohon DOM ke strings atau ke file.
  6. -
  7. {{jsxref("RegExp")}} bisa digunakan jika kamu selalu tau konten dari XML document sebelumnya. Kamu mungkin ingin menghapus jeda baris, jika Anda menggunakan RegEx untuk memindai berkenaan dengan jeda baris. Namun, metode ini adalah "pilihan terakhir" karena jika kode XML sedikit berubah, metode ini kemungkinan akan gagal.
  8. -
- -
-

Note: XMLHttpRequest sekarang dapat menafsirkan HTML untuk Anda menggunakan properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}. Baca artikel HTML dalam XMLHttpRequest untuk mempelajari cara untuk melakukannya.

-
- -

Memproses sebuah Properti responseText yang Berisi HTML Dokument

- -

Jika kamu mengunakan XMLHttpRequest untuk mendapatkan konten dari halaman web HTML jarak jauh. Properti {{domxref("XMLHttpRequest.responseText", "responseText")}} adalah sebuah string yang berisi data HTML mentah. Hal ini terbukti sulit untuk dimanipulasi dan dianalisi. Karenanya ada tiga cara utama untuk

- -

If you use XMLHttpRequest to get the content of a remote HTML webpage, the {{domxref("XMLHttpRequest.responseText", "responseText")}} property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. Ada tiga cara utama untuk menganalisis dan mengurai string HTML mentah ini:

- -
    -
  1. Use the XMLHttpRequest.responseXML property as covered in the article HTML in XMLHttpRequest.
  2. -
  3. Inject the content into the body of a document fragment via fragment.body.innerHTML and traverse the DOM of the fragment.
  4. -
  5. {{jsxref("RegExp")}} can be used if you always know the content of the HTML responseText beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.
  6. -
- -

Handling binary data

- -

Although {{domxref("XMLHttpRequest")}} is most commonly used to send and receive textual data, it can be used to send and receive binary content. There are several well tested methods for coercing the response of an XMLHttpRequest into sending binary data. These involve utilizing the {{domxref("XMLHttpRequest.overrideMimeType", "overrideMimeType()")}} method on the XMLHttpRequest object and is a workable solution.

- -
var oReq = new XMLHttpRequest();
-oReq.open("GET", url);
-// retrieve data unprocessed as a binary string
-oReq.overrideMimeType("text/plain; charset=x-user-defined");
-/* ... */
-
- -

However, more modern techniques are available, since the {{domxref("XMLHttpRequest.responseType", "responseType")}} attribute now supports a number of additional content types, which makes sending and receiving binary data much easier.

- -

For example, consider this snippet, which uses the responseType of "arraybuffer" to fetch the remote content into a {{jsxref("ArrayBuffer")}} object, which stores the raw binary data.

- -
var oReq = new XMLHttpRequest();
-
-oReq.onload = function(e) {
-  var arraybuffer = oReq.response; // not responseText
-  /* ... */
-}
-oReq.open("GET", url);
-oReq.responseType = "arraybuffer";
-oReq.send();
- -

For more examples check out the Sending and Receiving Binary Data page

- -

Monitoring progress

- -

XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.

- -

Support for DOM {{event("progress")}} event monitoring of XMLHttpRequest transfers follows the specification for progress events: these events implement the {{domxref("ProgressEvent")}} interface. The actual events you can monitor to determine the state of an ongoing transfer are:

- -
-
{{event("progress")}}
-
The amount of data that has been retrieved has changed.
-
{{event("load")}}
-
The transfer is complete; all data is now in the response
-
- -
var oReq = new XMLHttpRequest();
-
-oReq.addEventListener("progress", updateProgress);
-oReq.addEventListener("load", transferComplete);
-oReq.addEventListener("error", transferFailed);
-oReq.addEventListener("abort", transferCanceled);
-
-oReq.open();
-
-// ...
-
-// progress on transfers from the server to the client (downloads)
-function updateProgress (oEvent) {
-  if (oEvent.lengthComputable) {
-    var percentComplete = oEvent.loaded / oEvent.total * 100;
-    // ...
-  } else {
-    // Unable to compute progress information since the total size is unknown
-  }
-}
-
-function transferComplete(evt) {
-  console.log("The transfer is complete.");
-}
-
-function transferFailed(evt) {
-  console.log("An error occurred while transferring the file.");
-}
-
-function transferCanceled(evt) {
-  console.log("The transfer has been canceled by the user.");
-}
- -

Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest.

- -
Note: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.
- -

The progress event handler, specified by the updateProgress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. However, if the lengthComputable field is false, the total length is not known and will be zero.

- -

Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:

- -
var oReq = new XMLHttpRequest();
-
-oReq.upload.addEventListener("progress", updateProgress);
-oReq.upload.addEventListener("load", transferComplete);
-oReq.upload.addEventListener("error", transferFailed);
-oReq.upload.addEventListener("abort", transferCanceled);
-
-oReq.open();
-
- -
Note: Progress events are not available for the file: protocol.
- -
-

Note: Starting in {{Gecko("9.0")}}, progress events can now be relied upon to come in for every chunk of data received, including the last chunk in cases in which the last packet is received and the connection closed before the progress event is fired. In this case, the progress event is automatically fired when the load event occurs for that packet. This lets you now reliably monitor progress by only watching the "progress" event.

-
- -
-

Note: As of {{Gecko("12.0")}}, if your progress event is called with a responseType of "moz-blob", the value of response is a {{domxref("Blob")}} containing the data received so far.

-
- -

One can also detect all three load-ending conditions (abort, load, or error) using the loadend event:

- -
req.addEventListener("loadend", loadEnd);
-
-function loadEnd(e) {
-  console.log("The transfer finished (although we don't know if it succeeded or not).");
-}
-
- -

Note there is no way to be certain, from the information received by the loadend event, as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios.

- -

Submitting forms and uploading files

- -

Instances of XMLHttpRequest can be used to submit forms in two ways:

- - - -

Using the FormData API is the simplest and fastest, but has the disadvantage that data collected can not be stringified.
- Using only AJAX is more complex, but typically more flexible and powerful.

- -

Using nothing but XMLHttpRequest

- -

Submitting forms without the FormData API does not require other APIs for most use cases. The only case where you need an additional API is if you want to upload one or more files, where you use the {{domxref("FileReader")}} API.

- -

A brief introduction to the submit methods

- -

An html {{ HTMLElement("form") }} can be sent in four ways:

- - - -

Now, consider the submission of a form containing only two fields, named foo and baz. If you are using the POST method the server will receive a string similar to one of the following three examples, depending on the encoding type you are using:

- - - -

However, if you are using the GET method, a string like the following will be simply added to the URL:

- -
?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.
- -

A little vanilla framework

- -

All these effects are done automatically by the web browser whenever you submit a {{HTMLElement("form")}}. If you want to perform the same effects using JavaScript you have to instruct the interpreter about everything. Therefore, how to send forms in pure AJAX is too complex to be explained here in detail. For this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, and to upload files:

- -
-
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<title>Sending forms with pure AJAX &ndash; MDN</title>
-<script type="text/javascript">
-
-"use strict";
-
-/*\
-|*|
-|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polyfill ::
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
-\*/
-
-if (!XMLHttpRequest.prototype.sendAsBinary) {
-  XMLHttpRequest.prototype.sendAsBinary = function(sData) {
-    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
-    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
-      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
-    }
-    /* send as ArrayBufferView...: */
-    this.send(ui8Data);
-    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
-  };
-}
-
-/*\
-|*|
-|*|  :: AJAX Form Submit Framework ::
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
-|*|
-|*|  This framework is released under the GNU Public License, version 3 or later.
-|*|  https://www.gnu.org/licenses/gpl-3.0-standalone.html
-|*|
-|*|  Syntax:
-|*|
-|*|   AJAXSubmit(HTMLFormElement);
-\*/
-
-var AJAXSubmit = (function () {
-
-  function ajaxSuccess () {
-    /* console.log("AJAXSubmit - Success!"); */
-    console.log(this.responseText);
-    /* you can get the serialized data through the "submittedData" custom property: */
-    /* console.log(JSON.stringify(this.submittedData)); */
-  }
-
-  function submitData (oData) {
-    /* the AJAX request... */
-    var oAjaxReq = new XMLHttpRequest();
-    oAjaxReq.submittedData = oData;
-    oAjaxReq.onload = ajaxSuccess;
-    if (oData.technique === 0) {
-      /* method is GET */
-      oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/,
-          oData.segments.length > 0 ? "?" + oData.segments.join("&") : ""), true);
-      oAjaxReq.send(null);
-    } else {
-      /* method is POST */
-      oAjaxReq.open("post", oData.receiver, true);
-      if (oData.technique === 3) {
-        /* enctype is multipart/form-data */
-        var sBoundary = "---------------------------" + Date.now().toString(16);
-        oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
-        oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" +
-            oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
-      } else {
-        /* enctype is application/x-www-form-urlencoded or text/plain */
-        oAjaxReq.setRequestHeader("Content-Type", oData.contentType);
-        oAjaxReq.send(oData.segments.join(oData.technique === 2 ? "\r\n" : "&"));
-      }
-    }
-  }
-
-  function processStatus (oData) {
-    if (oData.status > 0) { return; }
-    /* the form is now totally serialized! do something before sending it to the server... */
-    /* doSomething(oData); */
-    /* console.log("AJAXSubmit - The form is now serialized. Submitting..."); */
-    submitData (oData);
-  }
-
-  function pushSegment (oFREvt) {
-    this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n";
-    this.owner.status--;
-    processStatus(this.owner);
-  }
-
-  function plainEscape (sText) {
-    /* How should I treat a text/plain form encoding?
-       What characters are not allowed? this is what I suppose...: */
-    /* "4\3\7 - Einstein said E=mc2" ----> "4\\3\\7\ -\ Einstein\ said\ E\=mc2" */
-    return sText.replace(/[\s\=\\]/g, "\\$&");
-  }
-
-  function SubmitRequest (oTarget) {
-    var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post";
-    /* console.log("AJAXSubmit - Serializing form..."); */
-    this.contentType = bIsPost && oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded";
-    this.technique = bIsPost ?
-        this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0;
-    this.receiver = oTarget.action;
-    this.status = 0;
-    this.segments = [];
-    var fFilter = this.technique === 2 ? plainEscape : escape;
-    for (var nItem = 0; nItem < oTarget.elements.length; nItem++) {
-      oField = oTarget.elements[nItem];
-      if (!oField.hasAttribute("name")) { continue; }
-      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
-      if (sFieldType === "FILE" && oField.files.length > 0) {
-        if (this.technique === 3) {
-          /* enctype is multipart/form-data */
-          for (nFile = 0; nFile < oField.files.length; nFile++) {
-            oFile = oField.files[nFile];
-            oSegmReq = new FileReader();
-            /* (custom properties:) */
-            oSegmReq.segmentIdx = this.segments.length;
-            oSegmReq.owner = this;
-            /* (end of custom properties) */
-            oSegmReq.onload = pushSegment;
-            this.segments.push("Content-Disposition: form-data; name=\"" +
-                oField.name + "\"; filename=\"" + oFile.name +
-                "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n");
-            this.status++;
-            oSegmReq.readAsBinaryString(oFile);
-          }
-        } else {
-          /* enctype is application/x-www-form-urlencoded or text/plain or
-             method is GET: files will not be sent! */
-          for (nFile = 0; nFile < oField.files.length;
-              this.segments.push(fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name)));
-        }
-      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
-        /* NOTE: this will submit _all_ submit buttons. Detecting the correct one is non-trivial. */
-        /* field type is not FILE or is FILE but is empty */
-        this.segments.push(
-          this.technique === 3 ? /* enctype is multipart/form-data */
-            "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
-          : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */
-            fFilter(oField.name) + "=" + fFilter(oField.value)
-        );
-      }
-    }
-    processStatus(this);
-  }
-
-  return function (oFormElement) {
-    if (!oFormElement.action) { return; }
-    new SubmitRequest(oFormElement);
-  };
-
-})();
-
-</script>
-</head>
-<body>
-
-<h1>Sending forms with pure AJAX</h1>
-
-<h2>Using the GET method</h2>
-
-<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
-  <fieldset>
-    <legend>Registration example</legend>
-    <p>
-      First name: <input type="text" name="firstname" /><br />
-      Last name: <input type="text" name="lastname" />
-    </p>
-    <p>
-      <input type="submit" value="Submit" />
-    </p>
-  </fieldset>
-</form>
-
-<h2>Using the POST method</h2>
-<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
-
-<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
-  <fieldset>
-    <legend>Registration example</legend>
-    <p>
-      First name: <input type="text" name="firstname" /><br />
-      Last name: <input type="text" name="lastname" />
-    </p>
-    <p>
-      <input type="submit" value="Submit" />
-    </p>
-  </fieldset>
-</form>
-
-<h3>Enctype: text/plain</h3>
-
-<form action="register.php" method="post" enctype="text/plain"
-    onsubmit="AJAXSubmit(this); return false;">
-  <fieldset>
-    <legend>Registration example</legend>
-    <p>
-      Your name: <input type="text" name="user" />
-    </p>
-    <p>
-      Your message:<br />
-      <textarea name="message" cols="40" rows="8"></textarea>
-    </p>
-    <p>
-      <input type="submit" value="Submit" />
-    </p>
-  </fieldset>
-</form>
-
-<h3>Enctype: multipart/form-data</h3>
-
-<form action="register.php" method="post" enctype="multipart/form-data"
-    onsubmit="AJAXSubmit(this); return false;">
-  <fieldset>
-    <legend>Upload example</legend>
-    <p>
-      First name: <input type="text" name="firstname" /><br />
-      Last name: <input type="text" name="lastname" /><br />
-      Sex:
-      <input id="sex_male" type="radio" name="sex" value="male" />
-      <label for="sex_male">Male</label>
-      <input id="sex_female" type="radio" name="sex" value="female" />
-      <label for="sex_female">Female</label><br />
-      Password: <input type="password" name="secret" /><br />
-      What do you prefer:
-      <select name="image_type">
-        <option>Books</option>
-        <option>Cinema</option>
-        <option>TV</option>
-      </select>
-    </p>
-    <p>
-      Post your photos:
-      <input type="file" multiple name="photos[]">
-    </p>
-    <p>
-      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" />
-      <label for="vehicle_bike">I have a bike</label><br />
-      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" />
-      <label for="vehicle_car">I have a car</label>
-    </p>
-    <p>
-      Describe yourself:<br />
-      <textarea name="description" cols="50" rows="8"></textarea>
-    </p>
-    <p>
-      <input type="submit" value="Submit" />
-    </p>
-  </fieldset>
-</form>
-
-</body>
-</html>
-
- -

To test this, create a page named register.php (which is the action attribute of these sample forms), and put the following minimalistic content:

- -
<?php
-/* register.php */
-
-header("Content-type: text/plain");
-
-/*
-NOTE: You should never use `print_r()` in production scripts, or
-otherwise output client-submitted data without sanitizing it first.
-Failing to sanitize can lead to cross-site scripting vulnerabilities.
-*/
-
-echo ":: data received via GET ::\n\n";
-print_r($_GET);
-
-echo "\n\n:: Data received via POST ::\n\n";
-print_r($_POST);
-
-echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n";
-if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; }
-
-echo "\n\n:: Files received ::\n\n";
-print_r($_FILES);
-
-
- -

The syntax to activate this script is simply:

- -
AJAXSubmit(myForm);
- -
Note: This framework uses the {{domxref("FileReader")}} API to transmit file uploads. This is a recent API and is not implemented in IE9 or below. For this reason, the AJAX-only upload is considered an experimental technique. If you do not need to upload binary files, this framework works fine in most browsers.
- -
Note: The best way to send binary content is via {{jsxref("ArrayBuffer", "ArrayBuffers")}} or {{domxref("Blob", "Blobs")}} in conjuncton with the {{domxref("XMLHttpRequest.send()", "send()")}} method and possibly the {{domxref("FileReader.readAsArrayBuffer()", "readAsArrayBuffer()")}} method of the FileReader API. But, since the aim of this script is to work with a stringifiable raw data, we used the {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} method in conjunction with the {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} method of the FileReader API. As such, the above script makes sense only when you are dealing with small files. If you do not intend to upload binary content, consider instead using the FormData API.
- -
Note: The non-standard sendAsBinary method is considered deprecated as of Gecko 31 {{geckoRelease(31)}} and will be removed soon. The standard send(Blob data) method can be used instead.
- -

Using FormData objects

- -

The {{domxref("XMLHttpRequest.FormData", "FormData")}} constructor lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primary use is in sending form data, but can also be used independently from a form in order to transmit user keyed data. The transmitted data is in the same format the form's submit() method uses to send data, if the form's encoding type were set to "multipart/form-data". FormData objects can be utilized in a number of ways with an XMLHttpRequest. For examples, and explanations of how one can utilize FormData with XMLHttpRequests, see the Using FormData Objects page. For didactic purposes here is a translation of the previous example transformed to use the FormData API. Note the brevity of the code:

- -
-
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" charset="UTF-8" />
-<title>Sending forms with FormData &ndash; MDN</title>
-<script>
-"use strict";
-
-function ajaxSuccess () {
-  console.log(this.responseText);
-}
-
-function AJAXSubmit (oFormElement) {
-  if (!oFormElement.action) { return; }
-  var oReq = new XMLHttpRequest();
-  oReq.onload = ajaxSuccess;
-  if (oFormElement.method.toLowerCase() === "post") {
-    oReq.open("post", oFormElement.action);
-    oReq.send(new FormData(oFormElement));
-  } else {
-    var oField, sFieldType, nFile, sSearch = "";
-    for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {
-      oField = oFormElement.elements[nItem];
-      if (!oField.hasAttribute("name")) { continue; }
-      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ?
-          oField.getAttribute("type").toUpperCase() : "TEXT";
-      if (sFieldType === "FILE") {
-        for (nFile = 0; nFile < oField.files.length;
-            sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
-      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
-        sSearch += "&" + escape(oField.name) + "=" + escape(oField.value);
-      }
-    }
-    oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true);
-    oReq.send(null);
-  }
-}
-</script>
-</head>
-<body>
-
-<h1>Sending forms with FormData</h1>
-
-<h2>Using the GET method</h2>
-
-<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
-  <fieldset>
-    <legend>Registration example</legend>
-    <p>
-      First name: <input type="text" name="firstname" /><br />
-      Last name: <input type="text" name="lastname" />
-    </p>
-    <p>
-      <input type="submit" value="Submit" />
-    </p>
-  </fieldset>
-</form>
-
-<h2>Using the POST method</h2>
-<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
-
-<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
-  <fieldset>
-    <legend>Registration example</legend>
-    <p>
-      First name: <input type="text" name="firstname" /><br />
-      Last name: <input type="text" name="lastname" />
-    </p>
-    <p>
-      <input type="submit" value="Submit" />
-    </p>
-  </fieldset>
-</form>
-
-<h3>Enctype: text/plain</h3>
-
-<p>The text/plain encoding is not supported by the FormData API.</p>
-
-<h3>Enctype: multipart/form-data</h3>
-
-<form action="register.php" method="post" enctype="multipart/form-data"
-    onsubmit="AJAXSubmit(this); return false;">
-  <fieldset>
-    <legend>Upload example</legend>
-    <p>
-      First name: <input type="text" name="firstname" /><br />
-      Last name: <input type="text" name="lastname" /><br />
-      Sex:
-      <input id="sex_male" type="radio" name="sex" value="male" />
-      <label for="sex_male">Male</label>
-      <input id="sex_female" type="radio" name="sex" value="female" />
-      <label for="sex_female">Female</label><br />
-      Password: <input type="password" name="secret" /><br />
-      What do you prefer:
-      <select name="image_type">
-        <option>Books</option>
-        <option>Cinema</option>
-        <option>TV</option>
-      </select>
-    </p>
-    <p>
-      Post your photos:
-      <input type="file" multiple name="photos[]">
-    </p>
-    <p>
-      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" />
-      <label for="vehicle_bike">I have a bike</label><br />
-      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" />
-      <label for="vehicle_car">I have a car</label>
-    </p>
-    <p>
-      Describe yourself:<br />
-      <textarea name="description" cols="50" rows="8"></textarea>
-    </p>
-    <p>
-      <input type="submit" value="Submit" />
-    </p>
-  </fieldset>
-</form>
-</body>
-</html>
-
- -
Note: As we said, {{domxref("FormData")}} objects are not stringifiable objects. If you want to stringify a submitted data, use the previous pure-AJAX example. Note also that, although in this example there are some file {{ HTMLElement("input") }} fields, when you submit a form through the FormData API you do not need to use the {{domxref("FileReader")}} API also: files are automatically loaded and uploaded.
- -

Get last modified date

- -
function getHeaderTime () {
-  console.log(this.getResponseHeader("Last-Modified"));  /* A valid GMTString date or null */
-}
-
-var oReq = new XMLHttpRequest();
-oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html");
-oReq.onload = getHeaderTime;
-oReq.send();
- -

Do something when last modified date changes

- -

Let's create two functions:

- -
function getHeaderTime () {
-  var nLastVisit = parseFloat(window.localStorage.getItem('lm_' + this.filepath));
-  var nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));
-
-  if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
-    window.localStorage.setItem('lm_' + this.filepath, Date.now());
-    isFinite(nLastVisit) && this.callback(nLastModif, nLastVisit);
-  }
-}
-
-function ifHasChanged(sURL, fCallback) {
-  var oReq = new XMLHttpRequest();
-  oReq.open("HEAD" /* use HEAD - we only need the headers! */, sURL);
-  oReq.callback = fCallback;
-  oReq.filepath = sURL;
-  oReq.onload = getHeaderTime;
-  oReq.send();
-}
- -

And to test:

- -
/* Let's test the file "yourpage.html"... */
-
-ifHasChanged("yourpage.html", function (nModif, nVisit) {
-  console.log("The page '" + this.filepath + "' has been changed on " + (new Date(nModif)).toLocaleString() + "!");
-});
- -

If you want to know if the current page has changed, please read the article about {{domxref("document.lastModified")}}.

- -

Cross-site XMLHttpRequest

- -

Modern browsers support cross-site requests by implementing the Cross-Origin Resource Sharing (CORS) standard. As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work. Otherwise, an INVALID_ACCESS_ERR exception is thrown.

- -

Bypassing the cache

- -

A cross-browser compatible approach to bypassing the cache is appending a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example:

- -
http://foo.com/bar.html -> http://foo.com/bar.html?12345
-http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345
-
- -

As the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.

- -

You can automatically adjust URLs using the following code:

- -
var oReq = new XMLHttpRequest();
-
-oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime());
-oReq.send(null);
- -

Security

- -

{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy.<policyname>.XMLHttpRequest.open</policyname> to allAccess to give specific sites cross-site access. This is no longer supported.")}}

- -

{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\"); to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}

- -

The recommended way to enable cross-site scripting is to use the Access-Control-Allow-Origin HTTP header in the response to the XMLHttpRequest.

- -

XMLHttpRequests being stopped

- -

If you conclude with an XMLHttpRequest receiving status=0 and statusText=null, this means the request was not allowed to be performed. It was UNSENT. A likely cause for this is when the XMLHttpRequest origin (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is subsequently open(). This case can happen, for example, when one has an XMLHttpRequest that gets fired on an onunload event for a window, the expected XMLHttpRequest is created when the window to be closed is still there, and finally sending the request (in otherwords, open()) when this window has lost its focus and another window gains focus. The most effective way to avoid this problem is to set a listener on the new window's {{event("activate")}} event which is set once the terminated window has its {{event("unload")}} event triggered.

- -

Workers

- -

Setting overrideMimeType does not work from a {{domxref("Worker")}}.  See {{bug(678057)}} for more details.  Other browsers may handle this differently.

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
- -

Browser compatibility

- - - -

{{Compat("api.XMLHttpRequest")}}

- -

See also

- -
    -
  1. MDN AJAX introduction
  2. -
  3. HTML in XMLHttpRequest
  4. -
  5. HTTP access control
  6. -
  7. How to check the security state of an XMLHTTPRequest over SSL
  8. -
  9. XMLHttpRequest - REST and the Rich User Experience
  10. -
  11. Microsoft documentation
  12. -
  13. "Using the XMLHttpRequest Object" (jibbering.com)
  14. -
  15. The XMLHttpRequest object: WHATWG specification
  16. -
diff --git a/files/id/web/css/@font-face/font-display/index.html b/files/id/web/css/@font-face/font-display/index.html deleted file mode 100644 index e7e8197792..0000000000 --- a/files/id/web/css/@font-face/font-display/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: font-display -slug: Web/CSS/@font-face/font-display -translation_of: Web/CSS/@font-face/font-display ---- -
{{CSSRef}}
- -

The font-display descriptor determines how a font face is displayed based on whether and when it is downloaded and ready to use.

- -

The font display timeline

- -

The font display timeline is based on a timer that begins the moment the user agent attempts to use a given downloaded font face. The timeline is divided into the three periods below which dictate the rendering behavior of any elements using the font face.

- -
-
Font block period
-
If the font face is not loaded, any element attempting to use it must render an invisible fallback font face. If the font face successfully loads during this period, it is used normally.
-
Font swap period
-
If the font face is not loaded, any element attempting to use it must render a fallback font face. If the font face successfully loads during this period, it is used normally.
-
Font failure period
-
If the font face is not loaded, the user agent treats it as a failed load causing normal font fallback.
-
- -

{{cssinfo}}

- -

Syntax

- -
/* Keyword values */
-font-display: auto;
-font-display: block;
-font-display: swap;
-font-display: fallback;
-font-display: optional;
- -

Values

- -
-
auto
-
The font display strategy is defined by the user agent.
-
block
-
Gives the font face a short block period and an infinite swap period.
-
swap
-
Gives the font face an extremely small block period and an infinite swap period.
-
fallback
-
Gives the font face an extremely small block period and a short swap period.
-
optional
-
Gives the font face an extremely small block period and no swap period.
-
- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -
@font-face {
-  font-family: ExampleFont;
-  src: url(/path/to/fonts/examplefont.woff) format('woff'),
-       url(/path/to/fonts/examplefont.eot) format('eot');
-  font-weight: 400;
-  font-style: normal;
-  font-display: fallback;
-}
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Fonts', '#font-display-desc', 'font-display')}}{{Spec2('CSS4 Fonts')}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("css.at-rules.font-face.font-display")}}

- -

See also

- - diff --git a/files/id/web/css/@font-face/index.html b/files/id/web/css/@font-face/index.html deleted file mode 100644 index 670ee39e20..0000000000 --- a/files/id/web/css/@font-face/index.html +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: '@font-face' -slug: Web/CSS/@font-face -tags: - - '@font-face' - - At-rule - - CSS - - CSS Fonts - - Fonts - - NeedsTranslation - - Reference - - TopicStub - - typography -translation_of: Web/CSS/@font-face ---- -
{{CSSRef}}
- -

The @font-face CSS at-rule specifies a custom font with which to display text; the font can be loaded from either a remote server or a locally-installed font on the user's own computer. If the local() function is provided, specifying a font name to look for on the user's computer, and the {{Glossary("user agent")}} finds a match, that local font is used. Otherwise, the font resource specified using the url() function is downloaded and used.

- -

By allowing authors to provide their own fonts, @font-face makes it possible to design content without being limited to the so-called "web-safe" fonts (that is, the fonts which are so common that they're considered to be universally available). The ability to specify the name of a locally-installed font to look for and use makes it possible to customize the font beyond the basics while making it possible to do so without relying on an Internet connection.

- -

It's common to use both url() and local() together, so that the user's installed copy of the font is used if available, falling back to downloading a copy of the font if it's not found on the user's device.

- -

The @font-face at-rule may be used not only at the top level of a CSS, but also inside any CSS conditional-group at-rule.

- -
@font-face {
-  font-family: "Open Sans";
-  src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"),
-       url("/fonts/OpenSans-Regular-webfont.woff") format("woff");
-}
- -

Syntax

- -

Descriptors

- -
-
{{cssxref("@font-face/font-display", "font-display")}}
-
Determines how a font face is displayed based on whether and when it is downloaded and ready to use.
-
{{cssxref("@font-face/font-family", "font-family")}}
-
Specifies a name that will be used as the font face value for font properties.
-
{{cssxref("@font-face/font-stretch", "font-stretch")}}
-
A {{cssxref("font-stretch")}} value. Since Firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-stretch: 50% 200%;
-
{{cssxref("@font-face/font-style", "font-style")}}
-
A {{cssxref("font-style")}} value. Since Firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-style: oblique 20deg 50deg;
-
{{cssxref("@font-face/font-weight", "font-weight")}}
-
A {{cssxref("font-weight")}} value. Since Firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-weight: 100 400;
-
{{cssxref("@font-face/font-variant", "font-variant")}}
-
A {{cssxref("font-variant")}} value.
-
{{cssxref("font-feature-settings", "font-feature-settings")}}
-
Allows control over advanced typographic features in OpenType fonts.
-
{{cssxref("@font-face/font-variation-settings", "font-variation-settings")}}
-
Allows low-level control over OpenType or TrueType font variations, by specifying the four letter axis names of the features to vary, along with their variation values.
-
{{cssxref("@font-face/src", "src")}}
-
-

Specifies the resource containing the font data. This can be a URL to a remote font file location or the name of a font on the user's computer.

- -

To provide the browser with a hint as to what format a font resource is — so it can select a suitable one — it is possible to include a format type inside a format() function:

- -
src: url(ideal-sans-serif.woff) format("woff"),
-     url(basic-sans-serif.ttf) format("truetype");
- -

The available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg".

-
-
{{cssxref("@font-face/unicode-range", "unicode-range")}}
-
The range of Unicode code points to be used from the font.
-
- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -

This example simply specifies a downloadable font to use, applying it to the entire body of the document:

- -

View the live example

- -
<html>
-<head>
-  <title>Web Font Sample</title>
-  <style type="text/css" media="screen, print">
-    @font-face {
-      font-family: "Bitstream Vera Serif Bold";
-      src: url("https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf");
-    }
-
-    body { font-family: "Bitstream Vera Serif Bold", serif }
-  </style>
-</head>
-<body>
-  This is Bitstream Vera Serif Bold.
-</body>
-</html>
-
- -

In this example, the user's local copy of "Helvetica Neue Bold" is used; if the user does not have that font installed (two different names are tried), then the downloadable font named "MgOpenModernaBold.ttf" is used instead:

- -
@font-face {
-  font-family: MyHelvetica;
-  src: local("Helvetica Neue Bold"),
-       local("HelveticaNeue-Bold"),
-       url(MgOpenModernaBold.ttf);
-  font-weight: bold;
-}
-
- -

Font MIME Types

- - - - - - - - - - - - - - - - - - - - - - - - - - -
FormatMIME type
TrueTypefont/ttf
OpenTypefont/otf
Web Open Font Formatfont/woff
Web Open Font Format 2font/woff2
- -

Notes

- - - -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WOFF2.0', '', 'WOFF2 font format')}}{{Spec2('WOFF2.0')}}Font format specification with new compression algorithm
{{SpecName('WOFF1.0', '', 'WOFF font format')}}{{Spec2('WOFF1.0')}}Font format specification
{{SpecName('CSS3 Fonts', '#font-face-rule', '@font-face')}}{{Spec2('CSS3 Fonts')}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("css.at-rules.font-face")}}

- -

See also

- - diff --git a/files/id/web/css/_colon_active/index.html b/files/id/web/css/_colon_active/index.html deleted file mode 100644 index 67d9357bef..0000000000 --- a/files/id/web/css/_colon_active/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: ':active' -slug: 'Web/CSS/:active' -translation_of: 'Web/CSS/:active' ---- -
{{CSSRef}}
- -

Rangkuman

- -

:active CSS pseudo-class menunjukkan kapan sebuah elemen telah diaktifasi oleh pengguna. Hal ini memperbolehkan halaman memberikan feedback (korelasi) sehingga aktivasi telah terdeteksi oleh browser. Ketika berinteraksi dengan mouse, hal ini secara tipikal waktu antara pengguna menekan tombol mouse dan merelasisasikannya.  :active pseudo-class juga secara tipical ditampilkan ketika menggunakan tombol tab pada keyboard. Hal ini sering digunakan pada element HTML {{HTMLElement("a")}} dan {{HTMLElement("button")}}, tetapi boleh jadi tidak terbatas pada hal tersebut.

- -

Style ini boleh jadi digunakan lebih oleh sebuah link-related pseudo-classes (tautan-terhubung dengan pseudo kelas) lainnya, yang mana merupakan {{cssxref(":link")}}, {{cssxref(":hover")}}, and {{cssxref(":visited")}}, ditampilkan dalam aturan bagian-bagiannya. Dalam memperoleh penampilan yang teraprofiasi dengan link, kamu membutuhkan menempatkan aturan :active setelah seluruh yang lainnya terhubungan dengan aturan link (link-related-rules), seperti diuraikan oleh LHVA-order:  :link — :visited — :hover — :active.

- -
Cataan: Pada system dengan multi tombol mouse, CSS 3 spesifik bahwa :active pseudo-class harus hanya diterapkan pada tombol utama; pada klik kanan mouse, ini secara tipikal kebanyakan pada tombol kiri.
- -

Contoh

- -
-

HTML

- -
<body>
-    <h1>:active CSS selector example</h1>
-    <p>The following link will turn lime during the time you click it and release the click: <a href="#">Mozilla Developer Network</a>.</p>
-</body>
- -

CSS

- -
body { background-color: #ffffc9 }
-a:link { color: blue } /* unvisited links */
-a:visited { color: purple } /* visited links */
-a:hover { font-weight: bold } /* user hovers */
-a:active { color: lime } /* active links */
-
- -
{{EmbedLiveSample('example',600,140)}}
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#active-pseudo', ':active')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Selectors', '#useraction-pseudos', ':active')}}{{Spec2('CSS3 Selectors')}}No change.
{{SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':active')}}{{Spec2('CSS2.1')}}No change.
{{SpecName('CSS1', '#anchor-pseudo-classes', ':active')}}{{Spec2('CSS1')}}Initial definition.
- -

Dukungan Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}4.05.01.0
Support on non-<a> elements1.0{{CompatGeckoDesktop("1.0")}}8.07.01.0
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1.0")}}6.06.01.0
Support on non-<a> elements1.0{{CompatGeckoMobile("1.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} [1]
-
- -

[1] Secara menyeluruh, Safari Mobile tidak menggunakan {{cssxref(":active")}} kesatuan yang tidak ada pada sebuah touchstart event handler pada elemen yang relevan atau pada {{HTMLElement("body")}}.

- -

Lihat juga

- - diff --git a/files/id/web/css/background-color/index.html b/files/id/web/css/background-color/index.html deleted file mode 100644 index f8198be9cc..0000000000 --- a/files/id/web/css/background-color/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: background-color -slug: Web/CSS/background-color -translation_of: Web/CSS/background-color ---- -
{{CSSRef}}
- -

Background-color CSS digunakan untuk seting warna latar belakang dari element yang di inginkan.

- -
{{EmbedInteractiveExample("pages/css/background-color.html")}}
- - - -

Syntax

- -
/* Keyword values */
-background-color: red;
-background-color: indigo;
-
-/* Hexadecimal value */
-background-color: #bbff00;    /* Fully opaque */
-background-color: #11ffee00;  /* Fully transparent */
-background-color: #11ffeeff;  /* Fully opaque */
-
-/* RGB value */
-background-color: rgb(255, 255, 128);        /* Fully opaque */
-background-color: rgba(117, 190, 218, 0.5);  /* 50% transparent */
-
-/* HSL value */
-background-color: hsl(50, 33%, 25%);         /* Fully opaque */
-background-color: hsla(50, 33%, 25%, 0.75);  /* 75% transparent */
-
-/* Special keyword values */
-background-color: currentcolor;
-background-color: transparent;
-
-/* Global values */
-background-color: inherit;
-background-color: initial;
-background-color: unset;
- -

Background-color menggunakan hanya satu jenis warna <color> nilai.

- -

Values

- -
-
{{cssxref("<color>")}}
-
The uniform color of the background. It is rendered behind any {{cssxref("background-image")}} that is specified, although the color will still be visible through any transparency in the image.
-
- -

Formal syntax

- -{{csssyntax}} - -

Contoh

- -

HTML

- -
<div class="exampleone">
-  Lorem ipsum dolor sit amet, consectetuer
-</div>
-
-<div class="exampletwo">
-  Lorem ipsum dolor sit amet, consectetuer
-</div>
-
-<div class="examplethree">
-  Lorem ipsum dolor sit amet, consectetuer
-</div>
- -

CSS

- -
.exampleone {
-  background-color: teal;
-  color: white;
-}
-
-.exampletwo {
-  background-color: rgb(153,102,153);
-  color: rgb(255,255,204);
-}
-
-.examplethree {
-  background-color: #777799;
-  color: #FFFFFF;
-}
-
- -

Result

- -

{{EmbedLiveSample("Examples", 200, 150)}}

- -

Accessibility concerns

- -

It is important to ensure that the contrast ratio between the background color and the color of the text placed over it is high enough that people experiencing low vision conditions will be able to read the content of the page.

- -

Color contrast ratio is determined by comparing the luminosity of the text and background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger.

- - - -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#background-color', 'background-color')}}{{Spec2('CSS3 Backgrounds')}}Though technically removing the transparent keyword, this doesn't change anything as it has been incorporated as a true {{cssxref("<color>")}}
{{SpecName('CSS2.1', 'colors.html#propdef-background-color', 'background-color')}}{{Spec2('CSS2.1')}}No change
{{SpecName('CSS1', '#background-color', 'background-color')}}{{Spec2('CSS1')}}Initial definition
- -
{{cssinfo}}
- -

Browser compatibility

- - - -

{{Compat("css.properties.background-color")}}

- -

See also

- - diff --git a/files/id/web/css/css_box_model/index.html b/files/id/web/css/css_box_model/index.html deleted file mode 100644 index 08152c9c16..0000000000 --- a/files/id/web/css/css_box_model/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: CSS Basic Box Model -slug: Web/CSS/CSS_Box_Model -tags: - - CSS - - CSS Box Model - - NeedsTranslation - - Overview - - Reference - - TopicStub -translation_of: Web/CSS/CSS_Box_Model ---- -
{{CSSRef}}
- -

CSS Basic Box Model is a module of CSS that defines the rectangular boxes—including their padding and margin—that are generated for elements and laid out according to the visual formatting model.

- -

Reference

- -

Properties

- -

Properties controlling the flow of content in a box

- -
- -
- -

Properties controlling the size of a box

- -
- -
- -

Properties controlling the margins of a box

- -
- -
- -

Properties controlling the paddings of a box

- -
- -
- -

Other properties

- -
- -
- -

Guides

- -
-
Introduction to the CSS box model
-
Explains one of the fundamental concept of CSS: the box model. This model defines how CSS lays out elements, including their content, padding, border, and margin areas.
-
Mastering margin collapsing
-
Sometimes, two adjacent margins are collapsed into one. This article describes the rules that govern when and why this happens, and how to control it.
-
Visual formatting model
-
Explains the visual formatting model.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}}Added margin-trim
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition.
diff --git a/files/id/web/css/css_box_model/introduction_to_the_css_box_model/index.html b/files/id/web/css/css_box_model/introduction_to_the_css_box_model/index.html deleted file mode 100644 index d81bae36e6..0000000000 --- a/files/id/web/css/css_box_model/introduction_to_the_css_box_model/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Introduction to the CSS basic box model -slug: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model -translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model ---- -
{{CSSRef}}
- -

When laying out a document, the browser's rendering engine represents each element as a rectangular box according to the standard CSS basic box model. CSS determines the size, position, and properties (color, background, border size, etc.) of these boxes.

- -

Every box is composed of four parts (or areas), defined by their respective edges: the content edge, padding edge, border edge, and margin edge.

- -

CSS Box model

- -

The content area, bounded by the content edge, contains the "real" content of the element, such as text, an image, or a video player. Its dimensions are the content width (or content-box width) and the content height (or content-box height). It often has a background color or background image.

- -

If the {{cssxref("box-sizing")}} property is set to content-box (default) and if the element is a block element, the content area's size can be explicitly defined with the {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, and {{cssxref("max-height")}} properties.

- -

The padding area, bounded by the padding edge, extends the content area to include the element's padding. Its dimensions are the padding-box width and the padding-box height.

- -

The thickness of the padding is determined by the {{cssxref("padding-top")}}, {{cssxref("padding-right")}}, {{cssxref("padding-bottom")}}, {{cssxref("padding-left")}}, and shorthand {{cssxref("padding")}} properties.

- -

The border area, bounded by the border edge, extends the padding area to include the element's borders. Its dimensions are the border-box width and the border-box height.

- -

The thickness of the borders are determined by the {{cssxref("border-width")}} and shorthand {{cssxref("border")}} properties. If the {{cssxref("box-sizing")}} property is set to border-box, the border area's size can be explicitly defined with the {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, and {{cssxref("max-height")}} properties. When there is a background ({{cssxref("background-color")}} or {{cssxref("background-image")}}) set on a box, it extends to the outer edge of the border (i.e. extends underneath the border in z-ordering). This default behavior can be altered with the {{cssxref("background-clip")}} css property.

- -

The margin area, bounded by the margin edge, extends the border area to include an empty area used to separate the element from its neighbors. Its dimensions are the margin-box width and the margin-box height.

- -

The size of the margin area is determined by the {{cssxref("margin-top")}}, {{cssxref("margin-right")}}, {{cssxref("margin-bottom")}}, {{cssxref("margin-left")}}, and shorthand {{cssxref("margin")}} properties. When margin collapsing occurs, the margin area is not clearly defined since margins are shared between boxes.

- -

Finally, note that for non-replaced inline elements, the amount of space taken up (the contribution to the height of the line) is determined by the {{cssxref('line-height')}} property, even though the borders and padding are still displayed around the content.

- -

See also

- - - -

Specification

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Box', '#intro')}}{{Spec2('CSS3 Box')}}
{{ SpecName("CSS2.1","box.html#box-dimensions")}}{{ Spec2('CSS2.1') }}Though more precisely worded, there is no practical change.
{{ SpecName("CSS1","#formatting-model")}}{{ Spec2('CSS1') }}Initial definition.
- -

See also

- - diff --git a/files/id/web/css/css_selectors/index.html b/files/id/web/css/css_selectors/index.html deleted file mode 100644 index 8bf3fb0034..0000000000 --- a/files/id/web/css/css_selectors/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: CSS Selectors -slug: Web/CSS/CSS_Selectors -tags: - - CSS - - CSS Selectors - - NeedsTranslation - - Overview - - Reference - - Selectors - - TopicStub -translation_of: Web/CSS/CSS_Selectors ---- -
{{CSSRef}}
- -

Selectors define to which elements a set of CSS rules apply.

- -

Dasar Selektor

- -
-
Type selectors (Jenis-Jenis Seleksi)
-
Dasar selektor ini memilih seluruh elemen sehingga ditampilkan dengan pemberian nama.
- Syntax: eltname
- Example: Input akan menampilkan sebuah elemen  {{HTMLElement('input')}}.
-
Class selectors (Selektor Class)
-
Dasar selektor ini memilih elemen yang didasarkan pada nilai attribut classnya.
- Syntax: .classname
- Example: .index akan menampilkan sebuah elemen yang mempunyai indeks class (seperti didefenisikan oleh sebuah attribut class="index" atau yang serupa).
-
ID selectors (selektor ID)
-
Dasar selektor ini memilih cabangan (nodes) didasarkan pada nilai attribut idnya. Bisa jadi hanya satu elemen dengan sebuah pemberian ID dalam sebuah dokumen.
- Syntax: #idname
- Example: #toc akan menampilkan elemen yang mempunyai id toc (seperti didefenisikan dengan atrribut id="toc" atau yang serupa).
-
Universal selectors (selektor seluruhnya)
-
Dasar selektor ini memilih seluruh nodes (cabangan). Ini juga ada dalam hanya sebuah satu-kumpulan nama (namespace) dan  dalam seluruh kumpulan nama (all-namespace) yang juga bervariasi.
- Syntax: * ns|* *|*
- Example: * akan menampilkan seluruh elemen dari dokumen.
-
Attribute selectors (selektor attribut)
-
Dasar selektor ini memilih nodes (cabangan)  didasarkan pada sebuah nilai dari atributnya.
- Syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
- Example: [autoplay] akan menampilkan seluruh elemen yang mempunyai attribut autoplay pengaturan (pada sebuah nilai).
-
- -

Combinators

- -
-
Adjacent sibling selectors
-
The '+' combinator selects nodes that immediately follow the former specified element.
- Syntax: A + B
- Example: ul + li will match any {{HTMLElement('li')}} that immediately follows a {{HTMLElement('ul')}}.
-
General sibling selectors
-
The '~' combinator selects nodes that follow (not necessarily immediately) the former specified element, if both elements shared the same parent.
- Syntax: A ~ B
- Example: p ~ span will match all {{HTMLElement('span')}} elements that follow a {{HTMLElement('p')}} element inside the same element.
-
Child selectors
-
The '>' combinator selects nodes that are direct children of the former specified element.
- Syntax: A > B
- Example: ul > li will match all {{HTMLElement('li')}} elements that are inside a {{HTMLElement('ul')}} element.
-
Descendant selectors
-
The ' ' combinator selects nodes that are children (not necessary direct children) of the former specified element.
- Syntax: A B
- Example: div span will match any {{HTMLElement('span')}} element that is inside a {{HTMLElement('div')}} element.
-
- -

Pseudo-elements

- -

Pseudo-elements are abstractions of the tree representing entities beyond what HTML does. For example, HTML doesn't have an element describing the first letter or line of a paragraph, or the marker of a list. Pseudo-elements represent these entities and allow CSS rules to be associated with them. that way, these entitities can be styled independently.

- -

Pseudo-classes

- -

Pseudo-classes allow to select elements based on information that is not contained in the document tree like a state or that is particularly complex to extract. E.g. they match if a link has been previously visited or not.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Selectors')}}{{Spec2('CSS4 Selectors')}} 
{{SpecName('CSS3 Selectors')}}{{Spec2('CSS3 Selectors')}} 
{{SpecName('CSS2.1', 'selector.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1')}}{{Spec2('CSS1')}}Initial definition
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop("1")}}3.03.51.0
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.5{{CompatGeckoMobile("1.9.2")}}{{CompatUnknown}}{{CompatUnknown}}3.2
-
diff --git a/files/id/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html b/files/id/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html deleted file mode 100644 index 9ec7339a95..0000000000 --- a/files/id/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: 'Using the :target pseudo-class in selectors' -slug: 'Web/CSS/CSS_Selectors/Using_the_:target_pseudo-class_in_selectors' -translation_of: 'Web/CSS/CSS_Selectors/Using_the_:target_pseudo-class_in_selectors' ---- -

When a URL points at a specific piece of a document, it can be difficult to ascertain. Find out how you can use some simple CSS to draw attention to the target of a URL and improve the user's experience. {{CSSRef}}

- -

Membantu mengidentifikasi tujuan dari sebuah tautan yang ditujukan pada sebuan bagian khusus sebuah dokumen, CSS3 Selectors mengenalkan {{ Cssxref(":target") }} pseudo-class.

- -

Penentuan Sebuah Target

- -

pseudo-class {{ Cssxref(":target") }} digunakan pada menampilkan target elemen dari sebuah URI berisikan sebuah pengidentifikasi menurut bagian bagian. Sebagai contoh, pada URI http://developer.mozilla.org/en/docs/Using_the_:target_selector#Example berisi bagian bagian pengidentifikasi #Example. Dalam HTML, pengidentifikasi ditemukan sebagai nilai dari masing masing id atau nama attribut, sejak keduanya membagi namespace (kelompok id atau nama) yang sama. Dengan begitu, contoh URI akan menunjukkan kop "Example" dalam dokumen ini.  

- -

Misalkan kamu berharap untuk menampilkan sebuah elemen h2 yang merupakan target sebuah URI, tetapi tidak menginginkan sesuatu jenis dari elemen lainnya untuk menemukan sebuah target tampilan. Ini cukup menyederhakan:

- -
h2:target {font-weight: bold;}
-
- -

Ini juga memungkinkan untuk membuat tampilan yang spesifik dari sebuah bagian bagian terkecil sebuah dokumen. Ini dilakukan menggunakan identifikasi nilai yang menemukan URI didalamnya. Dengan begitu, untuk menambahkan sebuah border pada #Example terpisah, kita dapat menuliskannya dengan:

- -
#Example:target {border: 1px solid black;}
- -

Menargetkan Seluruh Elemen

- -

Jika intensif (berkelanjutan) untuk membuat sebuah "blanket" tampilan yang akan diterapkan pada seluruh target element, selanjutnya seleksi secara umum yang dapat diterapkan didalamnya:

- -
:target {color: red;}
-
- -

Contoh

- -

Berikut contoh, ada lima poin tautan elemen dalam dokumen yang sama. Menyeleksi link "First", sebagai contoh, akan menyebabkan <h1 id="one"> menjadi target elemen. Catatan bahwa dokumen boleh melompat pada sebuah scroll posisi baru, selama target elemen ditempatkan pada posisi atas dari jendela browser jika memungkinkan. 

- -
-
<h4 id="one">...</h4> <p id="two">...</p>
-<div id="three">...</div> <a id="four">...</a> <em id="five">...</em>
-
-<a href="#one">First</a>
-<a href="#two">Second</a>
-<a href="#three">Third</a>
-<a href="#four">Fourth</a>
-<a href="#five">Fifth</a>
-
- -

Kesimpulan

- -

Dalam kasus dimana sebuah pengidentifikasi poin bagian bagian dari sebuah bagian dokumen, para pembaca bisa jadi dibingungkan tentang yang mana bagian dari dokumen yang mereka anggap untuk dapat dibaca (diseleksi). Dengan gaya target sebuah URI, kebingungan pembaca dapat dikurangi atau dihilangkan. 

- - - - - -
-

Original Document Information

- - -
diff --git a/files/id/web/css/flex-direction/index.html b/files/id/web/css/flex-direction/index.html deleted file mode 100644 index a706f2ac22..0000000000 --- a/files/id/web/css/flex-direction/index.html +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: flex-direction -slug: Web/CSS/flex-direction -translation_of: Web/CSS/flex-direction ---- -
{{CSSRef}}
- -


-

- -

flex-direction  adalah properti css yang menentukan sumbu utama dan arah (normal atau terbalik ) dari flex item yang ditempatkan di flex container / wadah .

- -
{{EmbedInteractiveExample("pages/css/flex-direction.html")}}
- - - -

Note that the values row and row-reverse are affected by the directionality of the flex container. If its {{HTMLAttrxRef("dir")}} attribute is ltr, row represents the horizontal axis oriented from the left to the right, and row-reverse from the right to the left; if the dir attribute is rtl, row represents the axis oriented from the right to the left, and row-reverse from the left to the right.

- -

Syntax

- -
/* The direction text is laid out in a line */
-flex-direction: row;
-
-/* Like <row>, but reversed */
-flex-direction: row-reverse;
-
-/* The direction in which lines of text are stacked */
-flex-direction: column;
-
-/* Like <column>, but reversed */
-flex-direction: column-reverse;
-
-/* Global values */
-flex-direction: inherit;
-flex-direction: initial;
-flex-direction: unset;
-
- -

Values

- -

The following values are accepted:

- -
-
row
-
The flex container's main-axis is defined to be the same as the text direction. The main-start and main-end points are the same as the content direction.
-
row-reverse
-
Behaves the same as row but the main-start and main-end points are permuted.
-
column
-
The flex container's main-axis is the same as the block-axis. The main-start and main-end points are the same as the before and after points of the writing-mode.
-
column-reverse
-
Behaves the same as column but the main-start and main-end are permuted.
-
- -

Accessibility concerns

- -

Using the flex-direction property with values of row-reverse or column-reverse will create a disconnect between the visual presentation of content and DOM order. This will adversely affect users experiencing low vision navigating with the aid of assistive technology such as a screen reader. If the visual (CSS) order is important, then screen reader users will not have access to the correct reading order.

- - - -

Formal definition

- -

{{cssinfo}}

- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -

Reversing flex container columns and rows

- -

HTML

- -
<h4>This is a Column-Reverse</h4>
-<div id="content">
-  <div class="box" style="background-color:red;">A</div>
-  <div class="box" style="background-color:lightblue;">B</div>
-  <div class="box" style="background-color:yellow;">C</div>
-</div>
-<h4>This is a Row-Reverse</h4>
-<div id="content1">
-  <div class="box1" style="background-color:red;">A</div>
-  <div class="box1" style="background-color:lightblue;">B</div>
-  <div class="box1" style="background-color:yellow;">C</div>
-</div>
-
- -

CSS

- -
#content {
-  width: 200px;
-  height: 200px;
-  border: 1px solid #c3c3c3;
-  display: flex;
-  flex-direction: column-reverse;
-}
-
-.box {
-  width: 50px;
-  height: 50px;
-}
-
-#content1 {
-  width: 200px;
-  height: 200px;
-  border: 1px solid #c3c3c3;
-  display: flex;
-  flex-direction: row-reverse;
-}
-
-.box1 {
-  width: 50px;
-  height: 50px;
-}
- -

Result

- -

{{EmbedLiveSample('Reversing_flex_container_columns_and_rows', '', '550')}}

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#flex-direction-property', 'flex-direction')}}{{Spec2('CSS3 Flexbox')}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("css.properties.flex-direction")}}

- -

See also

- - diff --git a/files/id/web/css/index.html b/files/id/web/css/index.html deleted file mode 100644 index c4f9c56adb..0000000000 --- a/files/id/web/css/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: CSS -slug: Web/CSS -translation_of: Web/CSS ---- -

Cascading Style Sheets, dikenal juga sebagai CSS, adalah bahasa stylesheet yang digunakan untuk merubah tampilan dokumen yang terulis dalam HTML atau XML (termasuk variasi bahasa XML seperti SVG atau XHTML). CSS menjelaskan bagaimana elemen terstruktur yang harus ditampilkan di layar, di kertas, dalam cara komunikasi, atau dalam media yang lain.

- -

CSS adalah salah satu dari bahasa inti dari open web (web berbasis terbuka) dan telah berstandar W3C specification. Dibangun dalam berbagai level, CSS1 sekarang sudah kuno, CSS2.1 direkomendasi dan CSS3, sekarang terbagi dalam modul kecil, bergerak dalam jalur standar.

- -
- - -
-
-

Dokumentasi dan tutorial

- -
-
Kunci konsep CSS
-
Menjelaskan syntax dan lembar bahasa dan memperkenalkan dasar-dasar seperti specificity dan inheritance, box model dan margin collapsing, stacking dan konteks block-formatting, atau initial, computed, used dan nilai actual. Entitas seperti CSS shorthand properties juga dijelaskan.
-
Panduan Pengembang CSS
-
Artikel yang membantu mempelajari tehnik CSS untuk membuat konten anda bersinar.
-
- -

Alat untuk pengembang CSS

- -
    -
  • W3C CSS Validation Service mengecek bila CSS yang diberikan adalah valid. Ini adalah alat debugging yang berguna.
  • -
  • Firebug extension milik Firefox, extensi populer yang mengizinkan untuk merubah secara langsung CSS dalam situs yang dilihat. Sangat praktis untuk beberapa perubahan, bahkan ekstensi ini berguna lebih banyak.
  • -
  • Web Developer extension milik FireFox juga mengizinkan melihat dan merubah scara langsung CSS dalam situs yang dilihat. lebih mudah daripada Firebug, walaupun kurang berguna.
  • -
  • EditCSS extension milik FireFox mengizinkan mengubah CSS dalam sidebar.
  • -
- - - - -
- -
- - -
    -
  • CSS Text-decoration Level 3 mencapai status Candidate Recommandation, termasuk properti text-decoration-* dan text-emphasis-*. Berikut lingk yang menjelaskan hal ini {{cssxref("text-shadow")}}. (August 1st, 2013)
  • -
  • Gecko sekarang suport {{cssxref("background-origin")}}: local. Ini tersedia dari Firefox 25 (dan siap juga dalam Nightly). (July 25th, 2013)
  • -
  • Pointer Events mencapai status Candidate Recommandation, berarti properti CSS touch-action, yang hanya dapat diimplementasikan pada IE10 (dengan prefiks -ms- ), sekarang bukan percobaan lagi. (May 6th, 2013)
  • -
  • Gecko suport flexible boxes yang telah ditambahkan untuk menyesuaikan spesifikasi terkini tercantum: dari Firefox 23 {{cssxref("::before")}} dan {{cssxref("::after")}} bersama dengan item fleksibel, dan semacam itu, dapat dipindah menggunakan {{cssxref("order")}} dan {{cssxref("align-self")}}. (May 3rd, 2013)
  • -
-
-
-
diff --git a/files/id/web/css/mask-border-width/index.html b/files/id/web/css/mask-border-width/index.html deleted file mode 100644 index 75f8f6ff0f..0000000000 --- a/files/id/web/css/mask-border-width/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: mask-border-width -slug: Web/CSS/mask-border-width -translation_of: Web/CSS/mask-border-width ---- -
{{CSSRef}}
- -

The mask-border-width CSS properti mengatur lebar elemen mask border.

- -

Syntax

- -
/* Keyword value */
-mask-border-width: auto;
-
-/* <length> value */
-mask-border-width: 1rem;
-
-/* <percentage> value */
-mask-border-width: 25%;
-
-/* <number> value */
-mask-border-width: 3;
-
-/* vertical | horizontal */
-mask-border-width: 2em 3em;
-
-/* top | horizontal | bottom */
-mask-border-width: 5% 15% 10%;
-
-/* top | right | bottom | left */
-mask-border-width: 5% 2em 10% auto;
-
-/* Global values */
-mask-border-width: inherit;
-mask-border-width: initial;
-mask-border-width: unset;
-
- -

The mask-border-width properti dapat ditentukan menggunakan satu, dua, tiga, atau empat nilai yang dipilih dari daftar nilai di bawah.

- - - -

Values

- -
-
<length-percentage>
-
Lebar batas topeng, ditetapkan sebagai {{cssxref ("<length>")}} atau {{cssxref ("<percentage>")}}. Persentase relatif terhadap lebar area perbatasan untuk offset horizontal dan tinggi area perbatasan untuk offset vertikal. Tidak boleh negatif.
-
<number>
-
Lebar batas topeng, ditentukan sebagai kelipatan yang sesuai {{cssxref("border-width")}}. Tidak boleh negatif.
-
auto
-
Lebar batas topeng dibuat sama dengan lebar atau tinggi intrinsik (mana yang dapat diterapkan) yang sesuai {{cssxref("mask-border-slice")}}. Jika gambar tidak memiliki dimensi intrinsik yang diperlukan, sesuai border-width digunakan sebagai gantinya.
-
- -

Formal definition

- -

{{cssinfo}}

- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -

Basic usage

- -

Properti ini tampaknya belum didukung di mana pun. Ketika akhirnya mulai didukung, itu akan berfungsi untuk menentukan lebar topeng perbatasan - mengatur ini ke nilai yang berbeda menjadi mask-border-slice akan menyebabkan irisan diskalakan agar sesuai dengan topeng perbatasan.

- -
mask-border-width: 30 fill;
- -

Browser berbasis Chromium mendukung versi lama properti ini — mask-box-image-width — dengan awalan:

- -
-webkit-mask-box-image-width: 20px;
- -
-

Note: The mask-border Halaman menampilkan contoh yang berfungsi (menggunakan properti topeng perbatasan awalan kedaluwarsa yang didukung di Chromium), sehingga Anda bisa mendapatkan gambaran tentang efeknya.

-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS Masks", "#propdef-mask-border-width", "mask-border-width")}}{{Spec2("CSS Masks")}}Initial definition
- -

Browser compatibility

- -

TBD

diff --git a/files/id/web/css/media_queries/using_media_queries/index.html b/files/id/web/css/media_queries/using_media_queries/index.html deleted file mode 100644 index 9fe60a8e8c..0000000000 --- a/files/id/web/css/media_queries/using_media_queries/index.html +++ /dev/null @@ -1,631 +0,0 @@ ---- -title: Media query CSS -slug: Web/CSS/Media_Queries/Using_media_queries -translation_of: Web/CSS/Media_Queries/Using_media_queries -original_slug: Web/Guide/CSS/Media_queries ---- -

Media query terdiri dari jenis media dan paling sedikit satu ekspresi yang membatasi lingkup style sheets dengan menggunakan fitur media, seperti lebar, tinggi, dan warna. Media query, ditambahkan di CSS3, memungkinkan tampilan konten disesuaikan dengan alat penampil tertentu tanpa harus mengubah konten itu sendiri.

- -

Sintaks

- -

Media query terdiri dari jenis media (media type) dan dapat, sesuai dengan spesifikasi CSS3, mengandung satu atau lebih ekspresi, diekspresikan sebagai fitur media, baik benar (true) atau salah (false).  Hasil query adalah benar jika jenis media yang disebutkan dalam media query cocok dengan jenis alat yang digunakan untuk menampilkan dokumen dan semua ekspresi di dalam media query adalah benar.

- -
<!-- Media query CSS pada elemen link -->
-<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />
-
-<!-- Media query CSS di dalam style sheet -->
-<style>
-@media (max-width: 600px) {
-  .facet_sidebar {
-    display: none;
-  }
-}
-</style>
- -

Ketika sebuah media query adalah benar, style sheet atau aturan style yang bersangkutan diterapkan, sesuai dengan aturan cascading normal. Style sheet dengan media query yang menempel pada tag <link> masih akan diunduh bahkan jika media query tersebut adalah salah (false) (namun tidak akan diterapkan).

- -

Kecuali jika Anda menggunakan operator not atau only, jenis media adalah opsional dan jenis all akan diterapkan.

- -

Operator logika

- -

Anda dapat merancang media query kompleks menggunakan operator logika, termasuk not, and, dan only. Operator and digunakan untuk menggabungkan banyak fitur media (media features) ke dalam satu media query tunggal, setiap fitur terkait harus benar (true) agar query benar (true). Operator not digunakan untuk menegasikan keseluruhan media query. Operator only digunakan untuk menerapkan suatu style hanya jika keseluruhan query cocok, berguna untuk mencegah browser lama menerapkan style-style tertentu. Jika Anda menggunakan operator-operator not atau only, Anda harus menyebutkan jenis media secara eksplisit.

- -

Anda juga dapat menggabungkan banyak media query dalam sebuah daftar terpisah koma; jika ada media query di dalam daftar yang benar (true), keseluruhan pernyataan media adalah benar (true). Hal ini setara dengan operator or.

- -

and

- -

Kata kunci and digunakan untuk menggabungkan banyak fitur media menjadi satu, seperti menggabungkan fitur media dengan jenis media. Media query dasar, sebuah fitur media tunggal dengan jenis media all secara implisit, dapat terlihat seperti ini:

- -
@media (min-width: 700px) { ... }
- -

Namun, jika, Anda menginginkan hal ini diterapkan hanya untuk tampilan lanskap, Anda dapat menggunakan operator and untuk menggabungkan fitur-fitur media tersebut.

- -
@media (min-width: 700px) and (orientation: landscape) { ... }
- -

Sekarang media query di atas hanya akan benar jika lebar viewport adalah 700px atau lebih dan dalam tampilan lanskap. Namun, jika, Anda hanya menginginkan hal ini untuk diterapkan jika jenis media tampilan adalah TV, Anda dapat menggabungkan fitur-fitur ini dengan jenis media menggunakan operator and.

- -
@media tv and (min-width: 700px) and (orientation: landscape) { ... }
- -

Sekarang, media query di atas hanya akan diterapkan jika jenis media adalah TV, lebar viewport adalah 700px atau lebih, dan tampilan adalah lanskap.

- -

daftar terpisah koma

- -

Daftar terpisah koma adalah seperti operator logika or ketika digunakan dalam media query. Ketika menggunakan daftar media query terpisah koma, jika ada media query yang benar (true), style or style sheet akan diterapkan. Setiap media query di dalam daftar terpisah koma diperlakukan sebagai query individual, dan setiap operator yang diterapkan pada satu media query tidak mempengaruhi yang lainnya. Ini berarti daftar media query terpisah koma dapat ditujukan  untuk fitur, jenis, dan kondisi media yang berbeda.

- -

Sebagai contoh, seandainya Anda ingin menerapkan seperangkat style jika alat penampil memiliki lebar minimum 700px atau alat genggam dalam moda lanskap, Anda dapat menulis sebagai berikut:

- -
@media (min-width: 700px), handheld and (orientation: landscape) { ... }
- -

Pada contoh di atas, jika saya menggunakan perangkat screen dengan lebar viewport 800px, pernyataan media akan benar (true) karena bagian pertama, yang diinterpetasikan sebagai @media all and (min-width: 700px) akan berlaku pada perangkat saya dan oleh karena itu benar (true), terlepas dari fakta bahwa perangkat screen saya akan gagal dalam pengecekan jenis media handheld di media query kedua. Demikian pula, jika saya menggunakan perangkat genggam handheld dalam moda lanskap dengan lebar viewport 500px, walaupun media query pertama gagal karena lebar viewport tidak sesuai, media query kedua akan berhasil dan oleh karena itu pernyataan media akan menghasilkan nilai benar (true).

- -

not

- -

Kata kunci not berlaku pada keseluruhan media query dan memberikan nilai benar (true) jika media query akan sebaliknya memberikan nilai salah (false) (seperti fitur query monochrome pada warna tampilan atau lebar layar 600px dengan min-width: 700px). Sebuah not hanya akan menegasikan media query yang ditetapkan dan bukan setiap media query jika ada dalam daftar media query terpisah koma. Kata kunci not tidak dapat digunakan untuk menegasikan sebuah fitur query individual, hanya untuk media query secara keseluruhan. Sebagai contoh, not dievaluasi paling akhir dalam query berikut ini:

- -
@media not all and (monochrome) { ... }
-
- -

Ini berarti bahwa query tersebut dievaluasi seperti ini:

- -
@media not (all and (monochrome)) { ... }
-
- -

... bukan seperti ini:

- -
@media (not all) and (monochrome) { ... }
- -

Sebagai contoh lain, lihat media query berikut ini:

- -
@media not screen and (color), print and (color)
-
- -

Yang dievaluasi seperti ini:

- -
@media (not (screen and (color))), print and (color)
- -

only

- -

Kata kunci only mencegah browser lama yang tidak mendukung media query dengan fitur media menerapkan style yang disediakan:

- -
<link rel="stylesheet" media="only screen and (color)" href="example.css" />
-
- -

Pseudo-BNF (untuk Anda yang gemar hal seperti ini)

- -
media_query_list: <media_query> [, <media_query> ]*
-media_query: [[only | not]? <media_type> [ and <expression> ]*]
-  | <expression> [ and <expression> ]*
-expression: ( <media_feature> [: <value>]? )
-media_type: all | aural | braille | handheld | print |
-  projection | screen | tty | tv | embossed
-media_feature: width | min-width | max-width
-  | height | min-height | max-height
-  | device-width | min-device-width | max-device-width
-  | device-height | min-device-height | max-device-height
-  | aspect-ratio | min-aspect-ratio | max-aspect-ratio
-  | device-aspect-ratio | min-device-aspect-ratio | max-device-aspect-ratio
-  | color | min-color | max-color
-  | color-index | min-color-index | max-color-index
-  | monochrome | min-monochrome | max-monochrome
-  | resolution | min-resolution | max-resolution
-  | scan | grid
- -

Media query adalah case insensitive.  Media query yang melibatkan jenis media yang tidak diketahui selalu salah (false).

- -
Catatan: Tanda kurung wajib digunakan di sekitar ekspresi; jika tidak digunakan akan mengakibatkan kesalahan.
- -

Fitur media

- -

Sebagian besar fitur media dapat diawali dengan "min-" atau "max-" untuk mengekspresikan batasan "lebih dari atau sama dengan" atau "kurang dari atau sama dengan".  Hal ini menghindari penggunaan simbol "<" dan ">", yang mungkin akan menyebabkan konflik dengan HTML dan XML.  Jika Anda  menggunakan fitur media tanpa nilai tertentu, ekspresi tersebut akan bernilai benar (true) jika nilai fitur adalah bukan-nol.

- -
Catatan: Jika sebuah fitur media tidak sesuai untuk alat di mana browser dijalankan, ekspresi yang melibatkan fitur media tersebut adalah selalu salah (false).  Sebagai contoh, meng-query rasio aspek dari suatu alat aural selalu bernilai salah (false).
- -

color

- -

Nilai: {{cssxref("<color>")}}
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max prefixes: ya

- -

Menunjukkan jumlah per komponen warna dari alat penampil.  Jika alat tersebut bukan alat yang memiliki warna, nilai ini adalah nol.

- -
Catatan: Jika komponen warna memiliki jumlah bit yang berbeda per komponen warna, angka yang paling kecillah yang digunakan.  Sebagai contoh, jika sebuat layar menggunakan 5 bit untuk biru dan merah dan 6 bit untuk hijau, maka alat tersebut dianggap menggunakan 5 bit per komponen warna.  Jika suat alat menggunakan warna terindeks, jumlah bit minimum per komponen warna dalam tabel warna yang digunakan.
- -

Contoh

- -

Untuk menerapkan style sheet pada semua alat berwarna:

- -
@media all and (color) { ... }
-
- -

Untuk menerapkan style sheet pada alat yang memiliki paling sedikit 4 bit per komponen warna:

- -
@media all and (min-color: 4) { ... }
-
- -

color-index

- -

Nila: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: ya

- -

Menunjukkan jumlah entri dalam tabel pencarian warna untuk alat penampil.

- -

Contoh

- -

Untuk menunjukkan bahwa suatu style sheet harus diterapkan pada semua alat yang menggunakan warna terindeks, Anda dapat melakukan:

- -
@media all and (color-index) { ... }
-
- -

Untuk menerapkan style sheet pada alat berwarna terindeks dengan paling sedikit 256 warna:

- -
<link rel="stylesheet" media="all and (min-color-index: 256)" href="http://foo.bar.com/stylesheet.css" />
-
- -

aspect-ratio

- -

Nilai: {{cssxref("<ratio>")}}
- Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
- Menerima prefiks min/max: ya

- -

Menggambarkan rasio aspek daerah tampilan dari alat penampil.  Nilai ini terdiri dari dua integer positif dipisahkan oleh karakter garis miring ("/").  Ini menunjukkan rasio piksel horisontal (angka pertama) terhadap piksel vertikal (angka kedua).

- -

Contoh

- -

Berikut ini memilih style sheet khusus untuk digunakan ketika daerah tampilan paling tidak selebar tingginya.

- -
@media screen and (min-aspect-ratio: 1/1) { ... }
- -

Ini memilih style ketika rasio aspek adalah 1:1 atau lebih. Dengan kata lain, style-style ini hanya akan diterapkan ketika area penampil adalah bujursangkar atau lanskap.

- -

device-aspect-ratio

- -

Nilai: {{cssxref("<ratio>")}}
- Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
- Menerima prefiks min/max: ya

- -

Menggambarkan rasio aspek dari alat penampil.  Nilai ini terdiri dari dua integer positif dipisahkan oleh karakter garis miring ("/").  Hal ini menunjukkan rasio piksel horisontal (yang pertama) terhadap piksel vertikal (yang kedua).

- -

Contoh

- -

Berikut ini memilih style sheet khusus yang digunakan untuk tampilan layar lebar.

- -
@media screen and (device-aspect-ratio: 16/9), screen and (device-aspect-ratio: 16/10) { ... }
- -

Ini memilih style ketika rasio aspek adalah 16:9 atau 16:10.

- -

device-height

- -

Nilai: {{cssxref("<length>")}}
- Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
- Menerima prefiks min/max: ya

- -

Menggambarkan tinggi alat penampil (berarti keseluruhan layar atau halaman, bukan hanya area render, seperti jendela dokumen).

- -

Contoh

- -

Untuk menerapkan style sheet pada sebuah dokument ketika ditampilkan pada layar yang memiliki panjang kurang dari 800 piksel, Anda dapat menggunakan ini:

- -
<link rel="stylesheet" media="screen and (max-device-height: 799px)" />
-
- -

device-width

- -

Nilai: {{cssxref("<length>")}}
- Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
- Menerima prefiks min/max: ya

- -

Menggambarkan lebar alat penampil (berarti keseluruhan layar atau halaman, bukan hanya area render, seperti jendela dokumen).

- -

Contoh

- -

Untuk menerapkan style sheet pada sebuah dokumen ketika ditampilkan pada layar yang memiliki lebar kurang dari 800 piksel wide, Anda dapat menggunakan ini:

- -
<link rel="stylesheet" media="screen and (max-device-width: 799px)" />
- -

grid

- -

Nilai: {{cssxref("<integer>")}}
- Media: all
- Menerima prefiks min/max: tidak

- -

Menentukan apakah alat penampil adalah sebuah alat grid atau bitmap.  Jika alat tersebut berbasis grid (seperti terminal TTY atau layar telepon dengan hanya satu font), nilai adalah 1.  Jika tidak, nilai adalah nol.

- -

Contoh

- -

Untuk menerapkan suatu style pada alat genggam dengan layar selebar 15-karakter atau kurang:

- -
@media handheld and (grid) and (max-width: 15em) { ... }
-
- -
Catatan: Unit "em" memiliki arti khusus untuk alat grid; karena lebar pasti "em" tidak dapat ditentukan, 1em diasumsikan selebar satu sel grid secara horisontal, dan tingginya satu sell secara vertikal.
- -

height

- -

Nilai: {{cssxref("<length>")}}
- Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
- Menerima prefiks min/max: ya

- -

Fitur media height (tinggi) menggambarkan tinggi permukaan rendering alat penampil (seperti tinggi viewport atau kotak halaman pada sebuah printer).

- -
Catatan: Ketika user mengubah ukuran window, Firefox mengganti style sheets dengan yang paling sesuai berdasarkan media query menggunakan fitur media width dan height.
- -

monochrome

- -

Nilai: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: ya

- -

Menunjukkan jumlah bit per piksel pada alat monokrom (keabuan).  Jika alat tersebut bukan monokrom, nilai alat tersebut adalah 0.

- -

Contoh

- -

Untuk menerapkan style sheet pada semua alat monokrom:

- -
@media all and (monochrome) { ... }
-
- -

Untuk menerapkan style sheet pada alat monokrom dengan paling sedikit 8 bit per piksel:

- -
@media all and (min-monochrome: 8) { ... }
-
- -

orientation

- -

Nilai: landscape | portrait
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: tidak

- -

Menunjukkan apakah viewport dalam mode lanskap (tampilan lebih lebar daripada tingginya) atau potret (tampilan lebih tinggi daripada lebarnya).

- -

Contoh

- -

Untuk menerapkan style sheet hanya pada orientasi potret:

- -
@media all and (orientation: portrait) { ... }
- -

resolution

- -

Nilai: {{cssxref("<resolution>")}}
- Media: {{cssxref("Media/Bitmap", "bitmap")}}
- Menerima prefiks min/max: ya

- -

Menunjukkan resolusi (kepadatan piksel) alat penampil. Resolution mungkin disebutkan dalam dots per inch (dpi - titik per inci) atau dots per centimeter (dpcm - titik per sentimeter).

- -

Contoh

- -

Untuk menerapkan style sheet pada alat dengan resolusi paling sedikit 300 dpi:

- -
@media print and (min-resolution: 300dpi) { ... }
-
- -

Untuk mengganti sintaks lama (min-device-pixel-ratio: 2):

- -
@media screen and (min-resolution: 2dppx) { ... }
- -

scan

- -

Nilai: progressiveinterlace
- Media: {{cssxref("Media/TV")}}
- Menerima prefiks min/max: tidak

- -

Menggambarkan proses pemindaian alat penampil televisi.

- -

Contoh

- -

Untuk menerapkan style sheet hanya pada televisi pemindai progresif:

- -
@media tv and (scan: progressive) { ... }
-
- -

width

- -

Nilai: {{cssxref("<length>")}}
- Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
- Menerima prefiks min/max: ya

- -

Fitur media width menggambarkan lebar permukaan rendering alat penampil (seperti lebar jendela dokumen, atau lebar kotak halaman sebuah printer).

- -
Catatan: Ketika user mengubah ukuran jendela, Firefox mengganti style sheets yang sesuai berdasarkan media query menggunakan fitur media width dan height.
- -

Contoh

- -

Jika Anda ingin menentukan sebuah style sheet untuk perangkat genggam, atau perangkat layar dengan lebar lebih besar dari 20em, Anda dapat menggunakan query ini:

- -
@media handheld and (min-width: 20em), screen and (min-width: 20em) { ... }
-
- -

Query Media ini menentukan style sheet yang berlaku untuk media cetak lebih lebar dari 8,5 inci:

- -
<link rel="stylesheet" media="print and (min-width: 8.5in)"
-    href="http://foo.com/mystyle.css" />
-
- -

Query ini menentukan style sheet yang digunakan saat lebar viewport adalah antara 500 dan 800 pixel:

- -
@media screen and (min-width: 500px) and (max-width: 800px) { ... }
-
- -

Fitur Media Spesifik Mozilla

- -

Mozilla menawarkan beberapa fitur media spesifik Gecko. Beberapa di antaranya mungkin diusulkan sebagai fitur media resmi.

- -

{{ h3_gecko_minversion("-moz-images-in-menus", "1.9.2") }}

- -

Nilai: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Meneriman prefiks min/max: tidak

- -

Jika perangkat memungkinkan gambar untuk muncul dalam menu, ini adalah 1; jika tidak, nilainya adalah 0. Ini berhubungan dengan pseudo-class CSS {{ cssxref(":-moz-system-metric(images-in-menus)") }}.

- -

{{ h3_gecko_minversion("-moz-mac-graphite-theme", "1.9.2") }}

- -

Nilai: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: no

- -

Jika user telah mengkonfigurasi perangkat mereka untuk menggunakan tampilan "Graphite" pada Mac OS X, ini adalah 1. Jika pengguna menggunakan tampilan biru standar, atau bukan pada Mac OS X, ini adalah 0.

- -

Ini berkaitan dengan pseudo-class CSS {{ cssxref(":-moz-system-metric(mac-graphite-theme)") }}.

- -

{{ h3_gecko_minversion("-moz-maemo-classic", "1.9.2") }}

- -

Nilai: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: tidak

- -

Jika user menggunakan Maemo dengan tema asli, ini adalah 1; jika menggunakan tema Fremantle yang lebih baru, ini adalah 0.

- -

Ini berkaitan dengan pseudo-class CSS {{ cssxref(":-moz-system-metric(maemo-classic)") }}.

- -

{{ h3_gecko_minversion("-moz-device-pixel-ratio", "2.0") }} {{ deprecated_inline("gecko&16") }}

- -

Nilai: {{cssxref("<number>")}}
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: ya

- -

Memberikan jumlah piksel perangkat per piksel CSS.

- -
-

Jangan gunakan fitur ini.

- -

Tapi gunakanlah fitur resolution dengan unit dppx.

- -


- -moz-device-pixel-ratio mungkin digunakan sebagai kompatibilitas dengan Firefox lebih tua daripada 16 dan -webkit-device-pixel-ratio dengan browser-browser berbasis WebKit yang tidak mendukung dppx.

- -

Contoh:

- -
@media (-webkit-min-device-pixel-ratio: 2), /* Browsers berbasis Webkit */
-       (min--moz-device-pixel-ratio: 2),    /* Browsers yang lebih tua (sebelum Firefox 16) */
-       (min-resolution: 2dppx),             /* Cara standar */
-       (min-resolution: 192dpi)             /* fallback dppx */ 
- -

Lihat artikel CSSWG ini untuk praktek kompatibilitas yang baik terkait resolution dan dppx.

-
- -
Catatan: Fitur media ini juga diimplementasikan oleh Webkit sebagai -webkit-device-pixel-ratio. Prefiks min dan max seperti diimplementasikan oleh Gecko dinamakan min--moz-device-pixel-ratio dan max--moz-device-pixel-ratio; tetapi prefiks yang sama seperti yang diimplementasikan oleh Webkit dinamakan -webkit-min-device-pixel-ratio dan -webkit-max-device-pixel-ratio.
- -

{{ h3_gecko_minversion("-moz-os-version", "25.0") }}

- -

Nilai: windows-xp | windows-vista | windows-win7 | windows-win8
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: tidak

- -

Menunjukkan versi sistem operasi mana yang sedang digunakan saat ini. Saat ini hanya diimplementasikan pada Windows. Nilai-nilai yang mungkin adalah:

- - - -

Ini disediakan untuk aplikasi skins dan kode chrome lainnya agar dapat beradaptasi untuk bekerja dengan baik dengan versi sistem operasi saat ini.

- -

{{ h3_gecko_minversion("-moz-scrollbar-end-backward", "1.9.2") }}

- -

Nilai: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: no

- -

Jika user interface perangkat menampilkan tombol panah kembali di akhir scrollbar, ini adalah 1. Jika tidak, bernilai 0.

- -

Ini berkaitan dengan pseudo-class CSS {{ cssxref(":-moz-system-metric(scrollbar-end-backward)") }}.

- -

{{ h3_gecko_minversion("-moz-scrollbar-end-forward", "1.9.2") }}

- -

Nilai: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Menerima prefiks min/max: tidak

- -

If the device's user interface displays a forward arrow button at the end of scrollbars, this is 1. Otherwise it's 0.

- -

This corresponds to the {{ cssxref(":-moz-system-metric(scrollbar-end-forward)") }} CSS pseudo-class.

- -

{{ h3_gecko_minversion("-moz-scrollbar-start-backward", "1.9.2") }}

- -

Value: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

If the device's user interface displays a backward arrow button at the beginning of scrollbars, this is 1. Otherwise it's 0.

- -

This corresponds to the {{ cssxref(":-moz-system-metric(scrollbar-start-backward)") }} CSS pseudo-class.

- -

{{ h3_gecko_minversion("-moz-scrollbar-start-forward", "1.9.2") }}

- -

Value: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

If the device's user interface displays a forward arrow button at the beginning of scrollbars, this is 1. Otherwise it's 0.

- -

This corresponds to the {{ cssxref(":-moz-system-metric(scrollbar-start-forward)") }} CSS pseudo-class.

- -

{{ h3_gecko_minversion("-moz-scrollbar-thumb-proportional", "1.9.2") }}

- -

Value: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

If the device's user interface displays the thumb of scrollbars proportionally (that is, sized based on the percentage of the document that is visible), this is 1. Otherwise it's 0.

- -

This corresponds to the {{ cssxref(":-moz-system-metric(scrollbar-thumb-proportional)") }} CSS pseudo-class.

- -

{{ h3_gecko_minversion("-moz-touch-enabled", "1.9.2") }}

- -

Value: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

If the device supports touch events (for a touch screen), this is 1. Otherwise it's 0.

- -

This corresponds to the {{ cssxref(":-moz-system-metric(touch-enabled)") }} CSS pseudo-class.

- -

Example

- -

You might use this to render your buttons slightly larger, for example, if the user is on a touch-screen device, to make them more finger-friendly.

- -

{{ h3_gecko_minversion("-moz-windows-classic", "1.9.2") }}

- -

Value: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

If the user is using Windows unthemed (in classic mode instead of using uxtheme), this is 1; otherwise it's 0.

- -

This corresponds to the {{ cssxref(":-moz-system-metric(windows-classic)") }} CSS pseudo-class.

- -

{{ h3_gecko_minversion("-moz-windows-compositor", "1.9.2") }}

- -

Value: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

If the user is using Windows with the DWM compositor, this is 1; otherwise it's 0.

- -

This corresponds to the {{ cssxref(":-moz-system-metric(windows-compositor)") }} CSS pseudo-class.

- -

{{ h3_gecko_minversion("-moz-windows-default-theme", "1.9.2") }}

- -

Value: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

If the user is currently using one of the default Windows themes (Luna, Royale, Zune, or Aero (including Vista Basic, Vista Advanced, and Aero Glass), this is 1. Otherwise it's 0.

- -

This corresponds to the {{ cssxref(":-moz-system-metric(windows-default-theme)") }} CSS pseudo-class.

- -

{{ h3_gecko_minversion("-moz-windows-glass", "21.0") }}

- -

Value: {{cssxref("<integer>")}}
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

If the user is using Windows Glass theme, this is 1; otherwise it's 0. Note that this only exists for Windows 7 and earlier.

- -

{{ h3_gecko_minversion("-moz-windows-theme", "2.0") }}

- -

Value: aero | luna-blue | luna-olive | luna-silver | royale | generic | zune
- Media: {{cssxref("Media/Visual")}}
- Accepts min/max prefixes: no

- -

Indicates which Windows theme is currently being used. Only available on Windows. Possible values are:

- - - -

This is provided for application skins and other chrome code to be able to adapt to work well with the current Windows theme.

- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome("21") }}{{ CompatGeckoDesktop("1.9.1") }}{{ CompatIE("9.0") }}{{ CompatOpera("9") }}{{ CompatSafari("4") }}
grid{{ CompatUnknown() }}{{ CompatNo() }} (grid media type is not supported){{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
resolution{{ CompatChrome("29") }}{{ CompatGeckoDesktop("1.9.1") }} supports {{cssxref("<integer>")}} values;
- {{ CompatGeckoDesktop("8.0") }} supports {{cssxref("<number>")}} values, as per the spec.
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
scan{{ CompatUnknown() }}{{ CompatNo() }} (tv media type is not supported){{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -

See also

- - diff --git a/files/id/web/css/reference/index.html b/files/id/web/css/reference/index.html deleted file mode 100644 index b8dfca3c45..0000000000 --- a/files/id/web/css/reference/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: Referensi CSS -slug: Web/CSS/Reference -translation_of: Web/CSS/Reference -original_slug: Web/CSS/referensi ---- -
{{CSSRef}}
- -

Gunakan referensi CSS ini untuk menelusuri indeks alfabetikal dari semua properti CSS umum, pseudo-classes, pseudo-elements, data types, dan at-rules. Anda juga dapat menulusuri konsep dasar and a list of selektor berdasarkan jenis. Juga ada referensi DOM-CSS / CSSOM.

- -

Basic rule syntax

- -

Style rule syntax

- -
style-rule ::=
-    selectors-list {
-      properties-list
-    }
-
- -

... where :

- -
selectors-list ::=
-    selector[:pseudo-class] [::pseudo-element]
-    [, selectors-list]
-
-properties-list ::=
-    [property : value] [; properties-list]
-
- -

See the index of selectors, pseudo-classes, and pseudo-elements below. The syntax for each specified value depends on the data type defined for each specified property.

- -

Style rule examples

- -
strong {
-  color: red;
-}
-
-div.menu-bar li:hover > ul {
-  display: block;
-}
-
- -

For a beginner-level introduction to the syntax of selectors, see our guide on CSS Selectors. Be aware that any syntax error in a rule definition invalidates the entire rule. Invalid rules are ignored by the browser. Note that CSS rule definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM (the rule management system) is object-based.

- -

At-rule syntax

- -

As the structure of at-rules varies widely, please see At-rule to find the syntax of the specific one you want.

- -

Keyword index

- -
-

Note: The property names in this index do not include the JavaScript names where they differ from the CSS standard names.

-
- -
{{CSS_Ref}}
- -

Selectors

- -

The following are the various selectors, which allow styles to be conditional based on various features of elements within the DOM.

- -

Basic selectors

- -

Basic selectors are fundamental selectors; these are the most basic selectors that are frequently combined to create other, more complex selectors.

- - - -

Grouping selectors

- -
-
Selector list A, B
-
Specifies that both A and B elements are selected. This is a grouping method to select several matching elements.
-
- -

Combinators

- -

Combinators are selectors that establish a relationship between two or more simple selectors, such as "A is a child of B" or "A is adjacent to B."

- -
-
Adjacent sibling combinator A + B
-
Specifies that the elements selected by both A and B have the same parent and that the element selected by B immediately follows the element selected by A horizontally.
-
General sibling combinator A ~ B
-
Specifies that the elements selected by both A and B share the same parent and that the element selected by A comes before—but not necessarily immediately before—the element selected by B.
-
Child combinator A > B
-
Specifies that the element selected by B is the direct child of the element selected by A.
-
Descendant combinator A B
-
Specifies that the element selected by B is a descendant of the element selected by A, but is not necessarily a direct child.
-
Column combinator A || B {{Experimental_Inline}}
-
Specifies that the element selected by B is located within the table column specified by A. Elements which span multiple columns are considered to be a member of all of those columns.
-
- -

Pseudo

- -
-
Pseudo classes :
-
Specifies a special state of the selected element(s).
-
Pseudo elements ::
-
Represents entities that are not included in HTML.
-
- -
-

See also: Selectors in the Selectors Level 4 specification.

-
- -

Concepts

- -

Syntax and semantics

- - - -

Values

- - - -

Layout

- - - -

DOM-CSS / CSSOM

- -

Major object types

- - - -

Important methods

- - - -

See also

- - - - - - diff --git a/files/id/web/css/text-transform/index.html b/files/id/web/css/text-transform/index.html deleted file mode 100644 index b9fbd65f0c..0000000000 --- a/files/id/web/css/text-transform/index.html +++ /dev/null @@ -1,307 +0,0 @@ ---- -title: text-transform -slug: Web/CSS/text-transform -translation_of: Web/CSS/text-transform ---- -
{{CSSRef}}
- -

Properti CSS text-transform menerangkan bagaimana mengatur teks sebuah elemen. Properti ini dapat digunakan untuk membuat sebuah teks menjadi besar atau kecil semua, atau membuat setiap kata dikapitalisasi.

- -
/* Nilai Kata-kunci */
-text-transform: capitalize;
-text-transform: uppercase;
-text-transform: lowercase;
-text-transform: none;
-text-transform: full-width;
-
-/* Nilai Global */
-text-transform: inherit;
-text-transform: initial;
-text-transform: unset;
-
- -

Properti text-transform memperhatikan peraturan khusus untuk setiap bahasa, seperti:

- - - -

Pilihan bahasa didefinisikan dengan atribut HTML lang atau dengan atribut XML xml:lang.

- -

Dukungan untuk kasus-kasus tertentu tidak sama untuk semua peramban, harap periksa tabel kompatibilitas peramban.

- -

{{cssinfo}}

- -

Syntax

- -
-
capitalize
-
-

Adalah kata kunci yang mengubah secara paksa huruf pertama dari setiap kata menjadi huruf besar. Karakter lainnya tidak berubah; huruf-huruf tersebut akan tetap seperti pertama kali dituliskan pada katanya. Sebuah huruf adalah karakter Unicode dari kategori Huruf atau Angka umum {{experimental_inline}} : pilihan ini tidak memasukkan tanda baca atau simbal pada awal kata.

- -
Penulis tidak seharusnya mengharapkan capitalize untuk mengikuti konvensi huruf besar untuk bahasa tertentu (seperti mengabaikan artikel dalam bahasa Inggris).
- -
Kata kunci capitalize kurang dispesifikasikan pada CSS 1 dan CSS 2.1. Terdapat perbedaan antara peramban untuk memperhitungkan huruf pertama (Firefox menganggap - dan _ sebagai huruf, tetapi peramban lain tidak. Baik Webkit dan Gecko tidak dengan tepat menanggap simbol berdasarkan huruf seperti sebagai benar-benar huruf. Internet Explorer 9 menerapkan definisi CSS 2 yang paling mendekati, tetapi dengan beberapa kasus sangat aneh). Dengan mendefinisikan bagaimana penerapan yang benar secara jelas, CSS Text Level 3 membersihkan kekacauan ini. Baris capitalize di tabel kompatibilitas peramban mempunyai informasi pada versi berapa mesin peramban mulai mendukung penerapan ini
-
-
uppercase
-
Adalah kata kunci yang mengubah semua karakter menjadi huruf besar.
-
lowercase
-
Adalah kata kunci yang mengubah semua karakter menjadi huruf kecil.
-
none
-
Adalah kata kunci yang mencegah perubahan dari semua karakter.
-
full-width {{experimental_inline}}
-
Adalah kata kunci yang mengharuskan penulisan karakter — biasanya ideogram dan tulisan latin — di dalam kotak persegi, yang membuat mereka dapat sejajar dalam tulisan Asia Timur kebanyakan (seperti bahasa Cina atau Jepang).
- -
- -

Sintaksis Formal

- -{{csssyntax}} - -

Contoh

- -

none

- -
<p>Kalimat Awal
-  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
-</p>
-<p>text-transform: none
-  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
-</p>
-
- -
span {
-  text-transform: none;
-}
-strong { float: right; }
- -

This demonstrates no text transformation.

- -

{{ EmbedLiveSample('none', '100%', '100px') }}

- -

capitalize (Umum)

- -
<p>Kalimat Awal
-  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
-</p>
-<p>text-transform: capitalize
-  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
-</p>
- -
span {
-  text-transform: capitalize;
-}
-strong { float: right; }
- -

Contoh ini menunjukkan kata yang dikapitalkan.

- -

{{ EmbedLiveSample('capitalize_(General)', '100%', '100px') }}

- -

capitalize (Tanda Baca)

- -
<p>Kalimat Awal
-  <strong>(this) “is” [a] –short– -test- «for» *the* _css_ ¿capitalize? ?¡transform!</strong>
-</p>
-<p>text-transform: capitalize
-  <strong><span>(this) “is” [a] –short– -test- «for» *the* _css_ ¿capitalize? ?¡transform!</span></strong>
-</p>
- -
span {
-  text-transform: capitalize;
-}
-strong { float: right; }
- -

Contoh ini mennjukkan bagaimana tanda baca di awal sebuah kata diabaikan. Kata kunci ini bekerja pada huruf pertama yang termasuk dalam bagian karakter Unicode dari kategori Huruf dan Angka umum.

- -

{{ EmbedLiveSample('capitalize_(Punctuation)', '100%', '100px') }}

- -

capitalize (Simbol)

- -
<p>Kalimat Awal
-  <strong>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</strong>
-</p>
-<p>text-transform: capitalize
-  <strong><span>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</span></strong>
-</p>
- -
span {
-  text-transform: capitalize;
-}
-strong { float: right; }
- -

Contoh ini menunjukkan bagaimana simbol di awal kata diabaikan. Kata kunci ini bekerja pada huruf pertama yang termasuk dalam bagian karakter Unicode dari kategori Huruf dan Angka umum.

- -

{{ EmbedLiveSample('capitalize_(Symbols)', '100%', '100px') }}

- -

capitalize (dwihuruf Belanda ij)

- -
<p>Kalimat Awal
-  <strong lang="nl">The Dutch word: "ijsland" starts with a digraph.</strong>
-</p>
-<p>text-transform: capitalize
-  <strong><span lang="nl">The Dutch word: "ijsland" starts with a digraph.</span></strong>
-</p>
- -
span {
-  text-transform: capitalize;
-}
-strong { float: right; }
- -

Contoh ini menunjukkan bagaimana dwihuruf bahasa Belanda ij harus diperlakukan sebagai huruf tunggal.

- -

{{ EmbedLiveSample('capitalize_(Dutch_ij_digraph)', '100%', '100px') }}

- -

uppercase (Umum)

- -
<p>Kalimat Awal
-  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
-</p>
-<p>text-transform: uppercase
-  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
-</p>
- -
span {
-  text-transform: uppercase;
-}
-strong { float: right; }
- -

Contoh ini menunjukkan bagaimana kalimat diubah menjadi huruf besar.

- -

{{ EmbedLiveSample('uppercase_(General)', '100%', '100px') }}

- -

uppercase (Huruf Vokal Yunani)

- -
<p>Kalimat Awal
-  <strong>Θα πάμε στο "Θεϊκό φαΐ" ή στη "Νεράιδα"</strong>
-</p>
-<p>text-transform: uppercase
-  <strong><span>Θα πάμε στο "Θεϊκό φαΐ" ή στη "Νεράιδα"</span></strong>
-</p>
- -
span {
-  text-transform: uppercase;
-}
-strong { float: right; }
- -

Contoh ini menunjukkan bagaimana huruf vokal bahasa Yunani, kecuali huruf disjungtif eta, kehilangan aksen, dan aksen pada huruf vokal pertama dari pasangan vokal menjadi diaeresis pada huruf vokal kedua.

- -

{{ EmbedLiveSample('uppercase_(Greek_Vowels)', '100%', '100px') }}

- -

lowercase (Umum)

- -
<p>Kalimat Awal
-  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
-</p>
-<p>text-transform: lowercase
-  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
-</p>
- -
span {
-  text-transform: lowercase;
-}
-strong { float: right; }
- -

Contoh ini menunjukkan bagaimana kalimat diubah menjadi huruf kecil.

- -

{{ EmbedLiveSample('lowercase_(General)', '100%', '100px') }}

- -

lowercase (Huruf Yunani Σ)

- -
<p>Kalimat Awal
-  <strong>Σ IS A greek LETTER that appears SEVERAL TIMES IN ΟΔΥΣΣΕΥΣ.</strong>
-</p>
-<p>text-transform: lowercase
-  <strong><span>Σ IS A greek LETTER that appears SEVERAL TIMES IN ΟΔΥΣΣΕΥΣ.</span></strong>
-</p>
- -
span {
-  text-transform: lowercase;
-}
-strong { float: right; }
- -

Contoh ini menunjukkan bagaimana karakter bahasa Yunani sigma (Σ) diubah menjadi huruf kecil sigma biasa (σ) atau varian akhir-kata (ς), tergantung kepada konteksnya.

- -

{{ EmbedLiveSample('lowercase_(Greek_Σ)', '100%', '100px') }}

- -

full-width (Umum)

- -
<p>Kalimat Awal
-  <strong>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@{|}~</strong>
-</p>
-<p>text-transform: full-width
-  <strong><span>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@{|}~</span></strong>
-</p>
- -
span {
-  text-transform: full-width;
-}
-strong { width: 100%; float: right; }
- -

Beberapa karakter mempunyai dua bentuk, yaitu lebar normal dan penuh, dengan kode nilai Unicode yang berbeda. Versi lebar-penuh digunakan untuk membuat penggabungan penulisan dengan karakter ideografi Asia dengan mulus.

- -

{{ EmbedLiveSample('full-width_(General)', '100%', '175px') }}

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('CSS4 Text', '#text-transform', 'text-transform')}}{{Spec2('CSS4 Text')}}Dari {{SpecName('CSS3 Text', '#text-transform', 'text-transform')}}, menambahkan kata kunci full-size-kana dan membolehkan kata kunci full-width digunakan bersama dengan kata kunci lainnya.
{{SpecName('CSS3 Text', '#text-transform', 'text-transform')}}{{Spec2('CSS3 Text')}}Dari {{SpecName('CSS2.1', 'text.html#caps-prop', 'text-transform')}}, memperluas cakupan huruf ke semua karakter Unicode dalam kategori Angka dan Huruf umum. Mengubah penerapan  capitalize ke huruf pertama kata, mengabaikan tanda baca atau simbol di awal. Menambahkan kata kunci full-width untuk membuat penggabungan penulisan dengan karakter ideografi dan alfabet menjadi mulus.
{{SpecName('CSS2.1', 'text.html#caps-prop', 'text-transform')}}{{Spec2('CSS2.1')}}Dari {{SpecName('CSS1', '#text-transform', 'text-transform')}}, memperluas cakupan huruf dengan tulisan bikameral non-latin.
{{SpecName('CSS1', '#text-transform', 'text-transform')}}{{Spec2('CSS1')}}Definisi awal
- -

Kompatibilitas Peramban

- -

 

- - - -

{{Compat("css.properties.text-transform")}}

- -

 

- -

Lihat juga

- - diff --git a/files/id/web/css/type_selectors/index.html b/files/id/web/css/type_selectors/index.html deleted file mode 100644 index 5302eef6eb..0000000000 --- a/files/id/web/css/type_selectors/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Type selectors -slug: Web/CSS/Type_selectors -translation_of: Web/CSS/Type_selectors ---- -
{{CSSRef("Selectors")}}
- -

Rangkuman

- -

Gaya seleksi CSS menampilkan elemen dengan nama node (bagian khusus nama elemen). Digunakan tersendiri, karenanya, sebuah tipe seleksi untuk sebuah nama node bagian terkecil menyeleksi seluruh bagian bagian dari tipe tersebut -- yang mana bahwa, dengan nama node tersebut -- didalam dokumen.

- -

Bentuk Penulisan

- -
element { style properties }
-
- -

Contoh

- -

CSS

- -
span {
-  background-color: DodgerBlue;
-  color: #ffffff;
-}
-
- -

HTML

- -
<span>Here's a span with some text.</span>
-<p>Here's a p with some text.</p>
-
- -

Hasil

- -

{{EmbedLiveSample('Example', 200, 100)}}

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('CSS4 Selectors', '#type-selectors', 'Type (tag name) selector')}}{{Spec2('CSS4 Selectors')}}Tanpa Perubahan
{{SpecName('CSS3 Selectors', '#type-selectors', 'type selectors')}}{{Spec2('CSS3 Selectors')}}Tanpa Perubahan
{{SpecName('CSS2.1', 'selector.html#type-selectors', 'type selectors')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#basic-concepts', 'type selectors')}}{{Spec2('CSS1')}}Defenisi Tanda
- -

Dukungan Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
diff --git a/files/id/web/events/index.html b/files/id/web/events/index.html deleted file mode 100644 index 3560bde99a..0000000000 --- a/files/id/web/events/index.html +++ /dev/null @@ -1,2310 +0,0 @@ ---- -title: Event reference -slug: Web/Events -tags: - - NeedsTranslation - - TopicStub - - events -translation_of: Web/Events ---- -

DOM Events are sent to notify code of interesting things that have taken place. Each event is represented by an object which is based on the {{domxref("Event")}} interface, and may have additional custom fields and/or functions used to get additional information about what happened. Events can represent everything from basic user interactions to automated notifications of things happening in the rendering model.

- -

This article offers a list of events that can be sent; some are standard events defined in official specifications, while others are events used internally by specific browsers; for example, Mozilla-specific events are listed so that add-ons can use them to interact with the browser.

- -

Standard events

- -

These events are defined in official Web specifications, and should be common across browsers. Each event is listed along with the interface representing the object sent to recipients of the event (so you can find information about what data is provided with each event) as well as a link to the specification or specifications that define the event.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
{{event("abort")}}{{domxref("UIEvent")}}DOM L3The loading of a resource has been aborted.
abort{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been terminated (not due to an error).
abort{{domxref("Event")}}IndexedDBA transaction has been aborted.
{{event("afterprint")}}{{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document has started printing or the print preview has been closed.
{{event("animationend")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation has completed.
{{event("animationiteration")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation is repeated.
{{event("animationstart")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation has started.
{{event("audioprocess")}}{{domxref("AudioProcessingEvent")}}{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
{{event("audioend")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has finished capturing audio for speech recognition.
{{event("audiostart")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has started to capture audio for speech recognition.
{{event("beforeprint")}} {{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document is about to be printed or previewed for printing.
{{event("beforeunload")}}{{domxref("BeforeUnloadEvent")}}HTML5  
{{event("beginEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element begins.
blocked IndexedDBAn open connection to a database is blocking a versionchange transaction on the same database.
{{event("blur")}}{{domxref("FocusEvent")}}DOM L3An element has lost focus (does not bubble).
{{event("boundary")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a word or sentence boundary
{{event("cached")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been downloaded, and the application is now cached.
{{event("canplay")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{event("canplaythrough")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{event("change")}}{{domxref("Event")}}DOM L2, HTML5The change event is fired for {{HTMLElement("input")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}} elements when a change to the element's value is committed by the user.
{{event("chargingchange")}}{{domxref("Event")}}Battery statusThe battery begins or stops charging.
{{event("chargingtimechange")}}{{domxref("Event")}}Battery statusThe chargingTime attribute has been updated.
{{event("checking")}}{{domxref("Event")}}OfflineThe user agent is checking for an update, or attempting to download the cache manifest for the first time.
{{event("click")}}{{domxref("MouseEvent")}}DOM L3A pointing device button has been pressed and released on an element.
close{{domxref("Event")}}WebSocketA WebSocket connection has been closed.
complete IndexedDB 
{{event("complete")}}{{domxref("OfflineAudioCompletionEvent")}}{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}The rendering of an {{domxref("OfflineAudioContext")}} is terminated.
{{event("compositionend")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text has been completed or canceled.
{{event("compositionstart")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{event("compositionupdate")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3A character is added to a passage of text being composed.
{{event("contextmenu")}}{{domxref("MouseEvent")}}HTML5The right button of the mouse is clicked (before the context menu is displayed).
{{event("copy")}}{{domxref("ClipboardEvent")}}ClipboardThe text selection has been added to the clipboard.
{{event("cut")}}{{domxref("ClipboardEvent")}}ClipboardThe text selection has been removed from the document and added to the clipboard.
{{event("dblclick")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is clicked twice on an element.
{{event("devicelight")}}{{domxref("DeviceLightEvent")}}Ambient Light EventsFresh data is available from a light sensor.
{{event("devicemotion")}}{{domxref("DeviceMotionEvent")}}Device Orientation EventsFresh data is available from a motion sensor.
{{event("deviceorientation")}}{{domxref("DeviceOrientationEvent")}}Device Orientation EventsFresh data is available from an orientation sensor.
{{event("deviceproximity")}}{{domxref("DeviceProximityEvent")}}Proximity EventsFresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).
{{event("dischargingtimechange")}}{{domxref("Event")}}Battery statusThe dischargingTime attribute has been updated.
DOMActivate {{deprecated_inline}}{{domxref("UIEvent")}}DOM L3A button, link or state changing element is activated (use {{event("click")}} instead).
DOMAttributeNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an attribute changed (use mutation observers instead).
DOMAttrModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3The value of an attribute has been modified (use mutation observers instead).
DOMCharacterDataModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A text or another CharacterData has changed (use mutation observers instead).
{{event("DOMContentLoaded")}}{{domxref("Event")}}HTML5The document has finished loading (but not its dependent resources).
DOMElementNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an element changed (use mutation observers instead).
DOMFocusIn {{deprecated_inline}}{{domxref("FocusEvent")}}DOM L3An element has received focus (use {{event("focus")}} or {{event("focusin")}} instead).
DOMFocusOut {{deprecated_inline}}{{domxref("FocusEvent")}}DOM L3An element has lost focus (use {{event("blur")}} or {{event("focusout")}} instead).
DOMNodeInserted {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been added as a child of another node (use mutation observers instead).
DOMNodeInsertedIntoDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been inserted into the document (use mutation observers instead).
DOMNodeRemoved {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from its parent node (use mutation observers instead).
DOMNodeRemovedFromDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from the document (use mutation observers instead).
DOMSubtreeModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A change happened in the document (use mutation observers instead).
{{event("downloading")}}{{domxref("Event")}}OfflineThe user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.
{{event("drag")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged (every 350ms).
{{event("dragend")}}{{domxref("DragEvent")}}HTML5A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection enters a valid drop target.
{{event("dragleave")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection leaves a valid drop target.
{{event("dragover")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged over a valid drop target (every 350ms).
{{event("dragstart")}}{{domxref("DragEvent")}}HTML5The user starts dragging an element or text selection.
{{event("drop")}}{{domxref("DragEvent")}}HTML5An element is dropped on a valid drop target.
{{event("durationchange")}}{{domxref("Event")}}HTML5 mediaThe duration attribute has been updated.
{{event("emptied")}}{{domxref("Event")}}HTML5 mediaThe media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("end_(SpeechRecognition)","end")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has disconnected.
{{event("end_(SpeechSynthesis)","end")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName("Web Speech API")}}The utterance has finished being spoken.
{{event("ended")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because the end of the media was reached.
{{event("ended_(Web_Audio)", "ended")}}{{domxref("Event")}}{{SpecName("Web Audio API")}} 
{{event("endEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element ends.
{{event("error")}}{{domxref("UIEvent")}}DOM L3A resource failed to load.
{{event("error")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has failed.
{{event("error")}}{{domxref("Event")}}OfflineAn error occurred while downloading the cache manifest or updating the content of the application.
{{event("error")}}{{domxref("Event")}}WebSocketA WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
{{event("error")}}{{domxref("Event")}}Server Sent EventsAn event source connection has been failed.
{{event("error")}}{{domxref("Event")}}IndexedDBA request caused an error and failed.
{{event("error_(SpeechRecognitionError)","error")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}A speech recognition error occurs.
{{event("error_(SpeechSynthesisError)","error")}}{{domxref("SpeechSynthesisErrorEvent")}}{{SpecName('Web Speech API')}}An error occurs that prevents the utterance from being successfully spoken.
{{event("focus")}}{{domxref("FocusEvent")}}DOM L3An element has received focus (does not bubble).
{{event("focusin")}}{{domxref("FocusEvent")}}DOM L3An element is about to receive focus (bubbles).
{{event("focusout")}}{{domxref("FocusEvent")}}DOM L3An element is about to lose focus (bubbles).
{{event("fullscreenchange")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenAn element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenIt was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("gamepadconnected")}}{{domxref("GamepadEvent")}}GamepadA gamepad has been connected.
{{event("gamepaddisconnected")}}{{domxref("GamepadEvent")}}GamepadA gamepad has been disconnected.
{{event("gotpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement receives pointer capture.
{{event("hashchange")}}{{domxref("HashChangeEvent")}}HTML5The fragment identifier of the URL has changed (the part of the URL after the #).
{{event("lostpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement lost pointer capture.
{{event("input")}}{{domxref("Event")}}HTML5The value of an element changes or the content of an element with the attribute contenteditable is modified.
{{event("invalid")}}{{domxref("Event")}}HTML5A submittable element has been checked and doesn't satisfy its constraints.
{{event("keydown")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down.
{{event("keypress")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down and that key normally produces a character value (use input instead).
{{event("keyup")}}{{domxref("KeyboardEvent")}}DOM L3A key is released.
{{event("languagechange")}}{{domxref("Event")}}{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }} 
{{event("levelchange")}}{{domxref("Event")}}Battery statusThe level attribute has been updated.
{{event("load")}}{{domxref("UIEvent")}}DOM L3A resource and its dependent resources have finished loading.
load{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been successful.
{{event("loadeddata")}}{{domxref("Event")}}HTML5 mediaThe first frame of the media has finished loading.
{{event("loadedmetadata")}}{{domxref("Event")}}HTML5 mediaThe metadata has been loaded.
{{event("loadend")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has stopped (after "error", "abort" or "load" have been dispatched).
{{event("loadstart")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has begun.
{{event("mark")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a named SSML "mark" tag.
message{{domxref("MessageEvent")}}WebSocketA message is received through a WebSocket.
message{{domxref("MessageEvent")}}Web WorkersA message is received from a Web Worker.
message{{domxref("MessageEvent")}}Web MessagingA message is received from a child (i)frame or a parent window.
message{{domxref("MessageEvent")}}Server Sent EventsA message is received through an event source.
{{event("message_(ServiceWorker)","message")}}{{domxref("ServiceWorkerMessageEvent")}} or {{domxref("ExtendableMessageEvent")}}, depending on context.Service WorkersA message is received from a service worker, or a message is received in a service worker from another context.
{{event("mousedown")}}{{domxref("MouseEvent")}}DOM L3A pointing device button (usually a mouse) is pressed on an element.
{{event("mouseenter")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached.
{{event("mouseleave")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached.
{{event("mousemove")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved over an element.
{{event("mouseout")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("mouseover")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mouseup")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is released over an element.
{{event("nomatch")}}{{domxref("SpeechRecognitionEvent")}}{{SpecName('Web Speech API')}}The speech recognition service returns a final result with no significant recognition.
{{event("notificationclick")}}{{domxref("NotificationEvent")}}{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}A system notification spawned by {{domxref("ServiceWorkerRegistration.showNotification()")}} has been clicked.
{{event("noupdate")}}{{domxref("Event")}}OfflineThe manifest hadn't changed.
{{event("obsolete")}}{{domxref("Event")}}OfflineThe manifest was found to have become a 404 or 410 page, so the application cache is being deleted.
{{event("offline")}}{{domxref("Event")}}HTML5 offlineThe browser has lost access to the network.
{{event("online")}}{{domxref("Event")}}HTML5 offlineThe browser has gained access to the network (but particular websites might be unreachable).
open{{domxref("Event")}}WebSocketA WebSocket connection has been established.
open{{domxref("Event")}}Server Sent EventsAn event source connection has been established.
{{event("orientationchange")}}{{domxref("Event")}}Screen OrientationThe orientation of the device (portrait/landscape) has changed
{{event("pagehide")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed from.
{{event("pageshow")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed to.
{{event("paste")}}{{domxref("ClipboardEvent")}}ClipboardData has been transferred from the system clipboard to the document.
{{event("pause")}}{{domxref("Event")}}HTML5 mediaPlayback has been paused.
{{event("pause_(SpeechSynthesis)", "pause")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance is paused part way through.
{{event("pointercancel")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer is unlikely to produce any more events.
{{event("pointerdown")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer enters the active buttons state.
{{event("pointerenter")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved inside the hit-testing boundary.
{{event("pointerleave")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved out of the hit-testing boundary.
{{event("pointerlockchange")}}{{domxref("Event")}}Pointer LockThe pointer was locked or released.
{{event("pointerlockerror")}}{{domxref("Event")}}Pointer LockIt was impossible to lock the pointer for technical reasons or because the permission was denied.
{{event("pointermove")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer changed coordinates.
{{event("pointerout")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device moved out of hit-testing boundary or leaves detectable hover range.
{{event("pointerover")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device is moved into the hit-testing boundary.
{{event("pointerup")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer leaves the active buttons state.
{{event("play")}}{{domxref("Event")}}HTML5 mediaPlayback has begun.
{{event("playing")}}{{domxref("Event")}}HTML5 mediaPlayback is ready to start after having been paused or delayed due to lack of data.
{{event("popstate")}}{{domxref("PopStateEvent")}}HTML5A session history entry is being navigated to (in certain cases).
{{event("progress")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestIn progress.
progress{{domxref("ProgressEvent")}}OfflineThe user agent is downloading resources listed by the manifest.
{{event("push")}}{{domxref("PushEvent")}}{{SpecName("Push API")}}A Service Worker has received a push message.
{{event("pushsubscriptionchange")}}{{domxref("PushEvent")}}{{SpecName("Push API")}}A PushSubscription has expired.
{{event("ratechange")}}{{domxref("Event")}}HTML5 mediaThe playback rate has changed.
{{event("readystatechange")}}{{domxref("Event")}}HTML5 and XMLHttpRequestThe readyState attribute of a document has changed.
{{event("repeatEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element is repeated.
{{event("reset")}}{{domxref("Event")}}DOM L2, HTML5A form is reset.
{{event("resize")}}{{domxref("UIEvent")}}DOM L3The document view has been resized.
{{event("resourcetimingbufferfull")}}{{domxref("Performance")}}Resource TimingThe browser's resource timing buffer is full.
{{event("result")}}{{domxref("SpeechRecognitionEvent")}}{{SpecName('Web Speech API')}}The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.
{{event("resume")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}A paused utterance is resumed.
{{event("scroll")}}{{domxref("UIEvent")}}DOM L3The document view or an element has been scrolled.
{{event("seeked")}}{{domxref("Event")}}HTML5 mediaA seek operation completed.
{{event("seeking")}}{{domxref("Event")}}HTML5 mediaA seek operation began.
{{event("select")}}{{domxref("UIEvent")}}DOM L3Some text is being selected.
{{event("selectstart")}}{{domxref("Event")}}{{ SpecName('Selection API')}}A selection just started.
{{event("selectionchange")}}{{domxref("Event")}}{{ SpecName('Selection API')}}The selection in the document has been changed.
{{event("show")}}{{domxref("MouseEvent")}}HTML5A contextmenu event was fired on/bubbled to an element that has a contextmenu attribute
{{event("soundend")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has stopped being detected.
{{event("soundstart")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has been detected.
{{event("speechend")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Speech recognised by the speech recognition service has stopped being detected.
{{event("speechstart")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Sound that is recognised by the speech recognition service as speech has been detected.
{{event("stalled")}}{{domxref("Event")}}HTML5 mediaThe user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("start_(SpeechRecognition)","start")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.
{{event("start_(SpeechSynthesis)","start")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance has begun to be spoken.
{{event("storage")}}{{domxref("StorageEvent")}}Web StorageA storage area (localStorage or sessionStorage) has changed.
{{event("submit")}}{{domxref("Event")}}DOM L2, HTML5A form is submitted.
success{{domxref("Event")}}IndexedDBA request successfully completed.
{{event("suspend")}}{{domxref("Event")}}HTML5 mediaMedia data loading has been suspended.
{{event("SVGAbort")}}{{domxref("SVGEvent")}}SVGPage loading has been stopped before the SVG was loaded.
{{event("SVGError")}}{{domxref("SVGEvent")}}SVGAn error has occurred before the SVG was loaded.
{{event("SVGLoad")}}{{domxref("SVGEvent")}}SVGAn SVG document has been loaded and parsed.
{{event("SVGResize")}}{{domxref("SVGEvent")}}SVGAn SVG document is being resized.
{{event("SVGScroll")}}{{domxref("SVGEvent")}}SVGAn SVG document is being scrolled.
{{event("SVGUnload")}}{{domxref("SVGEvent")}}SVGAn SVG document has been removed from a window or frame.
{{event("SVGZoom")}}{{domxref("SVGZoomEvent")}}SVGAn SVG document is being zoomed.
{{event("timeout")}}{{domxref("ProgressEvent")}}XMLHttpRequest 
{{event("timeupdate")}}{{domxref("Event")}}HTML5 mediaThe time indicated by the currentTime attribute has been updated.
{{event("touchcancel")}}{{domxref("TouchEvent")}}Touch EventsA touch point has been disrupted in an implementation-specific manners (too many touch points for example).
{{event("touchend")}}{{domxref("TouchEvent")}}Touch EventsA touch point is removed from the touch surface.
{{event("touchenter")}}{{domxref("TouchEvent")}}Touch Events RemovedA touch point is moved onto the interactive area of an element.
{{event("touchleave")}}{{domxref("TouchEvent")}}Touch Events RemovedA touch point is moved off the interactive area of an element.
{{event("touchmove")}}{{domxref("TouchEvent")}}Touch EventsA touch point is moved along the touch surface.
{{event("touchstart")}}{{domxref("TouchEvent")}}Touch EventsA touch point is placed on the touch surface.
{{event("transitionend")}}{{domxref("TransitionEvent")}}CSS TransitionsA CSS transition has completed.
{{event("unload")}}{{domxref("UIEvent")}}DOM L3The document or a dependent resource is being unloaded.
{{event("updateready")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
upgradeneeded IndexedDBAn attempt was made to open a database with a version number higher than its current version. A versionchange transaction has been created.
{{event("userproximity")}}{{domxref("UserProximityEvent")}}{{SpecName("Proximity Events")}}Fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not).
{{event("voiceschanged")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the {{event("voiceschanged")}} event fires.)
versionchange IndexedDBA versionchange transaction completed.
{{event("visibilitychange")}}{{domxref("Event")}}Page visibilityThe content of a tab has become visible or has been hidden.
{{event("volumechange")}}{{domxref("Event")}}HTML5 mediaThe volume has changed.
{{event("waiting")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because of a temporary lack of data.
{{event("wheel")}}{{gecko_minversion_inline("17")}}{{domxref("WheelEvent")}}DOM L3A wheel button of a pointing device is rotated in any direction.
- -

Non-standard events

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
{{event("afterscriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script has been executed.
{{event("beforescriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script is about to be executed.
{{event("beforeinstallprompt")}}{{domxref("Event")}}Chrome specificA user is prompted to save a web site to a home screen on mobile.
{{event("cardstatechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.cardState")}} property changes value.
{{event("change")}}{{domxref("DeviceStorageChangeEvent")}}Firefox OS specificThis event is triggered each time a file is created, modified or deleted on a given storage area.
{{event("connectionInfoUpdate")}} Firefox OS specificThe informations about the signal strength and the link speed have been updated.
{{event("cfstatechange")}} Firefox OS specificThe call forwarding state changes.
{{event("datachange")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object changes values.
{{event("dataerror")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object receive an error from the RIL.
{{event("DOMMouseScroll")}}{{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{event("wheel")}} instead)
dragdrop {{deprecated_inline}}DragEventMozilla specificAn element is dropped (use {{event("drop")}} instead).
dragexit {{deprecated_inline}}DragEventMozilla specificA drag operation is being ended(use {{event("dragend")}} instead).
draggesture {{deprecated_inline}}DragEventMozilla specificThe user starts dragging an element or text selection (use {{event("dragstart")}} instead).
{{event("icccardlockerror")}} Firefox OS specificthe {{domxref("MozMobileConnection.unlockCardLock()")}} or {{domxref("MozMobileConnection.setCardLock()")}} methods fails.
{{event("iccinfochange")}} Firefox OS specificThe {{domxref("MozMobileConnection.iccInfo")}} object changes.
{{event("localized")}} Mozilla SpecificThe page has been localized using data-l10n-* attributes.
{{event("mousewheel")}}{{deprecated_inline}} IE inventedThe wheel button of a pointing device is rotated.
{{event("MozAudioAvailable")}}{{domxref("Event")}}Mozilla specificThe audio buffer is full and the corresponding raw samples are available.
MozBeforeResize {{obsolete_inline}} Mozilla specificA window is about to be resized.
{{event("mozbrowseractivitydone")}} Firefox OS Browser API-specificSent when some activity has been completed (complete description TBD.)
{{event("mozbrowserasyncscroll")}} Firefox OS Browser API-specificSent when the scroll position within a browser {{HTMLElement("iframe")}} changes.
{{event("mozbrowseraudioplaybackchange")}} Firefox OS Browser API-specificSent when audio starts or stops playing within the browser {{HTMLElement("iframe")}} content.
{{event("mozbrowsercaretstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes.
{{event("mozbrowserclose")}} Firefox OS Browser API-specificSent when window.close() is called within a browser {{HTMLElement("iframe")}}.
{{event("mozbrowsercontextmenu")}} Firefox OS Browser API-specificSent when a browser {{HTMLElement("iframe")}} try to open a context menu.
{{event("mozbrowserdocumentfirstpaint")}} Firefox OS Browser API-specificSent when a new paint occurs on any document in the browser {{HTMLElement("iframe")}}.
{{event("mozbrowsererror")}} Firefox OS Browser API-specificSent when an error occured while trying to load a content within a browser iframe
{{event("mozbrowserfindchange")}} Firefox OS Browser API-specificSent when a search operation is performed on the browser {{HTMLElement("iframe")}} content (see HTMLIFrameElement search methods.)
{{event("mozbrowserfirstpaint")}} Firefox OS Browser API-specificSent when the {{HTMLElement("iframe")}} paints content for the first time (this doesn't include the initial paint from about:blank.)
{{event("mozbrowsericonchange")}} Firefox OS Browser API-specificSent when the favicon of a browser iframe changes.
{{event("mozbrowserlocationchange")}} Firefox OS Browser API-specificSent when an browser iframe's location changes.
{{event("mozbrowserloadend")}} Firefox OS Browser API-specificSent when the browser iframe has finished loading all its assets.
{{event("mozbrowserloadstart")}} Firefox OS Browser API-specificSent when the browser iframe starts to load a new page.
{{event("mozbrowsermanifestchange")}} Firefox OS Browser API-specificSent when a the path to the app manifest changes, in the case of a browser {{HTMLElement("iframe")}} with an open web app embedded in it.
{{event("mozbrowsermetachange")}} Firefox OS Browser API-specificSent when a {{htmlelement("meta")}} elelment is added to, removed from or changed in the browser {{HTMLElement("iframe")}}'s content.
{{event("mozbrowseropensearch")}} Firefox OS Browser API-specificSent when a link to a search engine is found.
{{event("mozbrowseropentab")}} Firefox OS Browser API-specificSent when a new tab is opened within a browser {{HTMLElement("iframe")}} as a result of the user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.)
{{event("mozbrowseropenwindow")}} Firefox OS Browser API-specificSent when {{domxref("window.open()")}} is called within a browser iframe.
{{event("mozbrowserresize")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}}'s window size has changed.
{{event("mozbrowserscroll")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}} content scrolls.
{{event("mozbrowserscrollareachanged")}} Firefox OS Browser API-specificSent when the available scrolling area  in the browser {{HTMLElement("iframe")}} changes. This can occur on resize and when the page size changes (while loading for example.)
{{event("mozbrowserscrollviewchange")}} Firefox OS Browser API-specificSent when asynchronous scrolling (i.e. APCZ) starts or stops.
{{event("mozbrowsersecuritychange")}} Firefox OS Browser API-specificSent when the SSL state changes within a browser iframe.
{{event("mozbrowserselectionstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes. Note that this is deprecated, and newer implementations use {{event("mozbrowsercaretstatechanged")}} instead.
{{event("mozbrowsershowmodalprompt")}} Firefox OS Browser API-specificSent when {{domxref("window.alert","alert()")}}, {{domxref("window.confirm","confirm()")}} or {{domxref("window.prompt","prompt()")}} are called within a browser iframe
{{event("mozbrowsertitlechange")}} Firefox OS Browser API-specificSent when the document.title changes within a browser iframe.
{{event("mozbrowserusernameandpasswordrequired")}} Firefox OS Browser API-specificSent when an HTTP authentification is requested.
{{event("mozbrowservisibilitychange")}} Firefox OS Browser API-specificSent when the visibility state of the current browser iframe {{HTMLElement("iframe")}} changes, for example due to a call to {{domxref("HTMLIFrameElement.setVisible","setVisible()")}}.
{{event("MozGamepadButtonDown")}} To be specifiedA gamepad button is pressed down.
{{event("MozGamepadButtonUp")}} To be specifiedA gamepad button is released.
{{event("MozMousePixelScroll")}} {{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)
{{event("MozOrientation")}} {{deprecated_inline}} Mozilla specificFresh data is available from an orientation sensor (see deviceorientation).
{{event("MozScrolledAreaChanged")}}{{domxref("UIEvent")}}Mozilla specificThe document view has been scrolled or resized.
{{event("moztimechange")}} Mozilla specificThe time of the device has been changed.
MozTouchDown {{deprecated_inline}} Mozilla specificA touch point is placed on the touch surface (use touchstart instead).
MozTouchMove {{deprecated_inline}} Mozilla specificA touch point is moved along the touch surface (use touchmove instead).
MozTouchUp {{deprecated_inline}} Mozilla specificA touch point is removed from the touch surface (use touchend instead).
{{event("alerting")}}{{domxref("CallEvent")}}To be specifiedThe correspondent is being alerted (his/her phone is ringing).
{{event("busy")}}{{domxref("CallEvent")}}To be specifiedThe line of the correspondent is busy.
{{event("callschanged")}}{{domxref("CallEvent")}}To be specifiedA call has been added or removed from the list of current calls.
onconnected {{event("connected")}}{{domxref("CallEvent")}}To be specifiedA call has been connected.
{{event("connecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to connect.
{{event("delivered")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been successfully delivered.
{{event("dialing")}}{{domxref("CallEvent")}}To be specifiedThe number of a correspondent has been dialed.
{{event("disabled")}} Firefox OS specificWifi has been disabled on the device.
{{event("disconnected")}}{{domxref("CallEvent")}}To be specifiedA call has been disconnected.
{{event("disconnecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to disconnect.
{{event("enabled")}} Firefox OS specificWifi has been enabled on the device.
{{event("error_(Telephony)","error")}}{{domxref("CallEvent")}}To be specifiedAn error occurred.
{{event("held")}}{{domxref("CallEvent")}}To be specifiedA call has been held.
{{event("holding")}}{{domxref("CallEvent")}}To be specifiedA call is about to be held.
{{event("incoming")}}{{domxref("CallEvent")}}To be specifiedA call is being received.
{{event("received")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been received.
{{event("resuming")}}{{domxref("CallEvent")}}To be specifiedA call is about to resume.
{{event("sent")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been sent.
{{event("statechange")}}{{domxref("CallEvent")}}To be specifiedThe state of a call has changed.
{{event("statuschange")}} Firefox OS specificThe status of the Wifi connection changed.
{{event("overflow")}}{{domxref("UIEvent")}}Mozilla specificAn element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible).
{{event("smartcard-insert")}} Mozilla specificA smartcard has been inserted.
{{event("smartcard-remove")}} Mozilla specificA smartcard has been removed.
{{event("stkcommand")}} Firefox OS specificThe STK Proactive Command is issued from ICC.
{{event("stksessionend")}} Firefox OS specificThe STK Session is terminated by ICC.
text Mozilla SpecificA generic composition event occurred.
{{event("underflow")}}{{domxref("UIEvent")}}Mozilla specificAn element is no longer overflowed by its content (only works for elements styled with overflow != visible).
uploadprogress {{deprecated_inline}}{{domxref("ProgressEvent")}}Mozilla SpecificUpload is in progress (see {{event("progress")}}).
-

{{event("ussdreceived")}}

-
 Firefox OS specificA new USSD message is received
{{event("voicechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.voice")}} object changes values.
- -

Mozilla-specific events

- -
-

Note: those events are never exposed to web content and can only be used in chrome content context.

-
- -

XUL events

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
{{event("broadcast")}} XULAn observer noticed a change to the attributes of a watched broadcaster.
{{event("CheckboxStateChange")}} XULThe state of a checkbox has been changed either by a user action or by a script (useful for accessibility).
close XULThe close button of the window has been clicked.
{{event("command")}} XULAn element has been activated.
{{event("commandupdate")}} XULA command update occurred on a commandset element.
{{event("DOMMenuItemActive")}} XULA menu or menuitem has been hovered or highlighted.
{{event("DOMMenuItemInactive")}} XULA menu or menuitem is no longer hovered or highlighted.
{{event("popuphidden")}}PopupEventXULA menupopup, panel or tooltip has been hidden.
{{event("popuphiding")}}PopupEventXULA menupopup, panel or tooltip is about to be hidden.
{{event("popupshowing")}}PopupEventXULA menupopup, panel or tooltip is about to become visible.
{{event("popupshown")}}PopupEventXULA menupopup, panel or tooltip has become visible.
{{event("RadioStateChange")}} XULThe state of a radio has been changed either by a user action or by a script (useful for accessibility).
{{event("ValueChange")}} XULThe value of an element has changed (a progress bar for example, useful for accessibility).
- -

Add-on-specific events

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
MozSwipeGesture Addons specificA touch point is swiped across the touch surface
MozMagnifyGestureStart Addons specificTwo touch points start to move away from each other.
MozMagnifyGestureUpdate Addons specificTwo touch points move away from each other (after a MozMagnifyGestureStart).
MozMagnifyGesture Addons specificTwo touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).
MozRotateGestureStart Addons specificTwo touch points start to rotate around a point.
MozRotateGestureUpdate Addons specificTwo touch points rotate around a point (after a MozRotateGestureStart).
MozRotateGesture Addons specificTwo touch points rotate around a point (after a sequence of MozRotateGestureUpdate).
MozTapGesture Addons specificTwo touch points are tapped on the touch surface.
MozPressTapGesture Addons specificA "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).
MozEdgeUIGesture Addons specificA touch point is swiped across the touch surface to invoke the edge UI (Win8 only).
MozAfterPaint Addons specificContent has been repainted.
DOMPopupBlocked Addons specificA popup has been blocked
DOMWindowCreated Addons specificA window has been created.
DOMWindowClose Addons specificA window is about to be closed.
DOMTitleChanged Addons specifcThe title of a window has changed.
DOMLinkAdded Addons specifcA link has been added a document.
DOMLinkRemoved Addons specifcA link has been removed inside from a document.
DOMMetaAdded Addons specificA meta element has been added to a document.
DOMMetaRemoved Addons specificA meta element has been removed from a document.
DOMWillOpenModalDialog Addons specificA modal dialog is about to open.
DOMModalDialogClosed Addons specificA modal dialog has been closed.
DOMAutoComplete Addons specificThe content of an element has been auto-completed.
DOMFrameContentLoaded Addons specificThe frame has finished loading (but not its dependent resources).
AlertActive Addons specificA notification element is shown.
AlertClose Addons specificA notification element is closed.
fullscreen Addons specificBrowser fullscreen mode has been entered or left.
sizemodechange Addons specificWindow has entered/left fullscreen mode, or has been minimized/unminimized.
MozEnteredDomFullscreen Addons specificDOM fullscreen mode has been entered.
SSWindowClosing Addons specificThe session store will stop tracking this window.
SSTabClosing Addons specificThe session store will stop tracking this tab.
SSTabRestoring Addons specificA tab is about to be restored.
SSTabRestored Addons specificA tab has been restored.
SSWindowStateReady Addons specificA window state has switched to "ready".
SSWindowStateBusy Addons specificA window state has switched to "busy".
tabviewsearchenabled Addons specificThe search feature of Panorama has been activated
tabviewsearchdisabled Addons specificThe search feature of Panorama has been deactivated
tabviewframeinitialized Addons specificThe frame container of Panorama has been initialized
tabviewshown Addons specificThe Panorama tab has been shown
tabviewhidden Addons specificThe Panorama tab has been hidden
TabOpen Addons specificA tab has been opened.
TabClose Addons specificA tab has been closed.
TabSelect Addons specificA tab has been selected.
TabShow Addons specificA tab has been shown.
TabHide Addons specificA tab has been hidden.
TabPinned Addons specificA tab has been pinned.
TabUnpinned Addons specificA tab has been unpinned.
- -

Developer tool-specific events

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
CssRuleViewRefreshed devtools specificThe "Rules" view of the style inspector has been updated.
CssRuleViewChanged devtools specificThe "Rules" view of the style inspector has been changed.
CssRuleViewCSSLinkClicked devtools specificA link to a CSS file has been clicked in the "Rules" view of the style inspector.
- -

Categories

- -

Animation events

- -

{{event("animationend")}}, {{event("animationiteration")}}, {{event("animationstart")}}, {{event("beginEvent")}}, {{event("endEvent")}}, {{event("repeatEvent")}}

- -

Battery events

- -

{{event("chargingchange")}} {{event("chargingtimechange")}}, {{event("dischargingtimechange")}} {{event("levelchange")}}

- -

Call events

- -

{{event("alerting")}}, {{event("busy")}}, {{event("callschanged")}} {{event("cfstatechange")}}, {{event("connected")}}, {{event("connecting")}}, {{event("dialing")}}, {{event("disconnected")}}, {{event("disconnecting")}}, {{event("error_(Telephony)","error")}}, {{event("held")}}, {{event("holding")}}, {{event("incoming")}}, {{event("resuming")}}, {{event("statechange")}}, {{event("voicechange")}}

- -

CSS events

- -

CssRuleViewRefreshed, CssRuleViewChanged, CssRuleViewCSSLinkClicked, {{event("transitionend")}}

- -

Database events

- -

abort, blocked, complete, {{event("error")}} (link), success, upgradeneeded, versionchange

- -

Document events

- -

DOMLinkAdded, DOMLinkRemoved, DOMMetaAdded, DOMMetaRemoved, DOMWillOpenModalDialog, DOMModalDialogClosed, {{event("unload")}}

- -

DOM mutation events

- -

DOMAttributeNameChanged, DOMAttrModified, DOMCharacterDataModified, {{event("DOMContentLoaded")}}, DOMElementNameChanged, DOMNodeInserted, DOMNodeInsertedIntoDocument, DOMNodeRemoved, DOMNodeRemovedFromDocument, DOMSubtreeModified

- -

Drag events

- -

{{event("drag")}}, dragdrop, {{event("dragend")}}, {{event("dragenter")}}, dragexit, draggesture, {{event("dragleave")}}, {{event("dragover")}}, {{event("dragstart")}}, {{event("drop")}}

- -

Element events

- -

{{event("invalid")}}, {{event("overflow")}}, {{event("underflow")}}, DOMAutoComplete, {{event("command")}}, {{event("commandupdate")}}

- -

Focus events

- -

{{event("blur")}}, {{event("change")}}, DOMFocusIn, DOMFocusOut, {{event("focus")}}, {{event("focusin")}}, {{event("focusout")}}

- -

Form events

- -

{{event("reset")}}, {{event("submit")}}

- -

Frame events

- -

{{event("mozbrowserclose")}}, {{event("mozbrowsercontextmenu")}}, {{event("mozbrowsererror")}}, {{event("mozbrowsericonchange")}}, {{event("mozbrowserlocationchange")}}, {{event("mozbrowserloadend")}}, {{event("mozbrowserloadstart")}}, {{event("mozbrowseropenwindow")}}, {{event("mozbrowsersecuritychange")}}, {{event("mozbrowsershowmodalprompt")}} (link), {{event("mozbrowsertitlechange")}}, DOMFrameContentLoaded

- -

Input device events

- -

{{event("click")}}, {{event("contextmenu")}}, {{event("DOMMouseScroll")}}, {{event("dblclick")}}, {{event("gamepadconnected")}}, {{event("gamepaddisconnected")}}, {{event("keydown")}}, {{event("keypress")}}, {{event("keyup")}}, {{event("MozGamepadButtonDown")}}, {{event("MozGamepadButtonUp")}}, {{event("mousedown")}}, {{event("mouseenter")}}, {{event("mouseleave")}}, {{event("mousemove")}}, {{event("mouseout")}}, {{event("mouseover")}}, {{event("mouseup")}}, {{event("mousewheel")}}, {{event("MozMousePixelScroll")}}, {{event("pointerlockchange")}}, {{event("pointerlockerror")}},{{event("wheel")}}

- -

Media events

- -

{{event("audioprocess")}}, {{event("canplay")}}, {{event("canplaythrough")}}, {{event("durationchange")}}, {{event("emptied")}}, {{event("ended")}}, {{event("ended_(Web_Audio)", "ended")}}, {{event("loadeddata")}}, {{event("loadedmetadata")}}, {{event("MozAudioAvailable")}}, {{event("pause")}}, {{event("play")}}, {{event("playing")}}, {{event("ratechange")}}, {{event("seeked")}}, {{event("seeking")}}, {{event("stalled")}}, {{event("suspend")}}, {{event("timeupdate")}}, {{event("volumechange")}}, {{event("waiting")}}, {{event("complete")}}

- - - -

{{event("DOMMenuItemActive")}}, {{event("DOMMenuItemInactive")}}

- -

Network events

- -

{{event("datachange")}}, {{event("dataerror")}}, {{event("disabled")}}, {{event("enabled")}}, {{event("offline")}}, {{event("online")}}, {{event("statuschange")}}, {{event("connectionInfoUpdate")}},

- -

Notification events

- -

AlertActive, AlertClose

- -

Pointer events

- -

{{event("pointerover")}}, {{event("pointerenter")}}, {{event("pointerdown")}}, {{event("pointermove")}}, {{event("pointerup")}}, {{event("pointercancel")}}, {{event("pointerout")}}, {{event("pointerleave")}}, {{event("gotpointercapture")}}, {{event("lostpointercapture")}}

- - - -

{{event("popuphidden")}}, {{event("popuphiding")}}, {{event("popupshowing")}}, {{event("popupshown")}}, DOMPopupBlocked

- -

Printing events

- -

{{event("afterprint")}}, {{event("beforeprint")}}

- -

Progress events

- -

abort, {{event("error")}}, load, {{event("loadend")}}, {{event("loadstart")}}, {{event("progress")}}, progress, {{event("timeout")}}, uploadprogress

- -

Resource events

- -

{{event("abort")}}, {{event("cached")}}, {{event("error")}}, {{event("load")}}

- -

Script events

- -

{{event("afterscriptexecute")}}, {{event("beforescriptexecute")}}

- -

Sensor events

- -

{{event("compassneedscalibration")}}, {{event("devicelight")}}, {{event("devicemotion")}}, {{event("deviceorientation")}}, {{event("deviceproximity")}}, {{event("MozOrientation")}}, {{event("orientationchange")}}, {{event("userproximity")}}

- -

Session history events

- -

{{event("pagehide")}}, {{event("pageshow")}}, {{event("popstate")}}

- -

Smartcard events

- -

{{event("icccardlockerror")}}, {{event("iccinfochange")}}, {{event("smartcard-insert")}}, {{event("smartcard-remove")}}, {{event("stkcommand")}}, {{event("stksessionend")}}, {{event("cardstatechange")}}

- -

SMS and USSD events

- -

{{event("delivered")}}, {{event("received")}}, {{event("sent")}}, {{event("ussdreceived")}}

- -

Storage events

- -

{{event("change")}} (see {{anch("Non-standard events")}}), {{event("storage")}}

- -

SVG events

- -

{{event("SVGAbort")}}, {{event("SVGError")}}, {{event("SVGLoad")}}, {{event("SVGResize")}}, {{event("SVGScroll")}}, {{event("SVGUnload")}}, {{event("SVGZoom")}}

- -

Tab events

- -

tabviewsearchenabled, tabviewsearchdisabled, tabviewframeinitialized, tabviewshown, tabviewhidden, TabOpen, TabClose, TabSelect, TabShow, TabHide, TabPinned, TabUnpinned, SSTabClosing, SSTabRestoring, SSTabRestored, {{event("visibilitychange")}}

- -

Text events

- -

{{event("compositionend")}}, {{event("compositionstart")}}, {{event("compositionupdate")}}, {{event("copy")}}, {{event("cut")}}, {{event("paste")}}, {{event("select")}}, text

- -

Touch events

- -

MozEdgeUIGesture, MozMagnifyGesture, MozMagnifyGestureStart, MozMagnifyGestureUpdate, MozPressTapGesture, MozRotateGesture, MozRotateGestureStart, MozRotateGestureUpdate, MozSwipeGesture, MozTapGesture, MozTouchDown, MozTouchMove, MozTouchUp, {{event("touchcancel")}}, {{event("touchend")}}, {{event("touchenter")}}, {{event("touchleave")}}, {{event("touchmove")}}, {{event("touchstart")}}

- -

Update events

- -

{{event("checking")}}, {{event("downloading")}}, {{event("error")}}, {{event("noupdate")}}, {{event("obsolete")}}, {{event("updateready")}}

- -

Value change events

- -

{{event("broadcast")}}, {{event("CheckboxStateChange")}}, {{event("hashchange")}}, {{event("input")}}, {{event("RadioStateChange")}}, {{event("readystatechange")}}, {{event("ValueChange")}}

- -

View events

- -

fullscreen, {{event("fullscreenchange")}}, {{event("fullscreenerror")}}, MozEnteredDomFullscreen, {{event("MozScrolledAreaChanged")}}, {{event("resize")}}, {{event("scroll")}}, sizemodechange

- -

Websocket events

- -

close, {{event("error")}}, message, open

- -

Window events

- -

DOMWindowCreated, DOMWindowClose, DOMTitleChanged, MozBeforeResize {{obsolete_inline}}, SSWindowClosing, SSWindowStateReady, SSWindowStateBusy, close

- -

Uncategorized events

- -

{{event("beforeunload")}}, {{event("localized")}}, message, message, message, MozAfterPaint, {{event("moztimechange")}}, open, {{event("show")}}

- -

See also

- - diff --git a/files/id/web/guide/api/index.html b/files/id/web/guide/api/index.html deleted file mode 100644 index 4e0e34c483..0000000000 --- a/files/id/web/guide/api/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Guide to Web APIs -slug: Web/Guide/API -tags: - - API - - Guide - - Landing - - NeedsTranslation - - TopicStub - - Web -translation_of: Web/Guide/API ---- -

Here you'll find links to each of the guides introducing and explaining each of the APIs that make up the Web development architecture.

- -

Web APIs from A to Z

- -

{{ListGroups}}

- -

See also

- - diff --git a/files/id/web/guide/graphics/index.html b/files/id/web/guide/graphics/index.html deleted file mode 100644 index e9d34ad59a..0000000000 --- a/files/id/web/guide/graphics/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Grafis dalam web -slug: Web/Guide/Graphics -tags: - - 2D - - 3D - - Canvas - - Grafik - - MDN - - OpenGL - - Web - - WebRTC -translation_of: Web/Guide/Graphics -original_slug: Web/Guide/Grafis ---- -

Situs web moderen dan aplikasi sering membutuhkan tampilan grafis. Gambar statis dapat dengan mudah ditamilkan dengan menggunakan elemen {{HTMLElement("img")}} , atau mengatur tampilan background dari elemen HTML dengan menggunakan properti css {{cssxref("background-image")}}. anda sering menginginkan tampilan grafis melayang, atau memanipulasi gambar dari gambar nyatanya. Artikel ini memberikan wawasan tentang bagaimana anda dapat melakukannya

- -
-
-

Grafik 2D

- -
-
Canvas
-
Elemen {{HTMLElement("canvas")}} menyediakan API untuk menggambar grafik 2D menggunakan javascript.
-
SVG
-
Scalable Vector Graphics (SVG) memungkinkan anda menggunakan garis, kurva, dan bentuk geometris lain untuk membuat grafik. Dengan menghindari penggunaan bitmap, Anda dapat membuat gambar yang bersih dengan skala berbagai ukuran.
-
- -

Lihat Semua... 

-
- -
-

Grafik 3D

- -
-
WebGL
-
Sebuah panduan untuk memulai menggunakan WebGL, API grafis 3D untuk Web. Teknologi ini memungkinkan anda menggunakan standar OpenGL ES dalam konten Web.
-
- -

Video

- -
-
Menggunakan HTML5 audio dan video
-
Embedding video dan / atau audio di halaman web dan mengendalikan pemutaran nya.
-
WebRTC
-
RTC pada WebRTC artinya Real-Time Communications, teknologi yang memungkinkan streaming audio/video serta berbagi data antar browser pengguna (peers).
-
-
-
diff --git a/files/id/web/guide/html/html5/index.html b/files/id/web/guide/html/html5/index.html deleted file mode 100644 index 48e2349af7..0000000000 --- a/files/id/web/guide/html/html5/index.html +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: HTML5 -slug: Web/Guide/HTML/HTML5 -tags: - - HTML - - HTML5 - - NeedsTranslation - - References - - TopicStub - - Web Development -translation_of: Web/Guide/HTML/HTML5 ---- -

HTML5 adalah evolusi terbaru dari standard yang mendefinisikan HTML. Istilah ini merepresentasikan dua konsep yang berbeda:

- - - -

Dirancang untuk dapat digunakan oleh semua pengembang Web Terbuka, Berikut ini adalah tautan halaman referensi ke beberapa resource tentang teknologi HTML5, diklasifikasikan ke dalam beberapa kelompok berdasarkan fungsinya masing-masing.

- - - -
-
-

Semantik

- -
-
"Sections" dan "outlines" pada HTML5
-
Sebuah tampilan pada elemen baru yaitu outline dan section pada HTML5: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} and {{HTMLElement("aside")}}.
-
Menggunakan fungsi "audio"  dan "video" pada HTML5
-
Elemen {{HTMLElement("audio")}} dan {{HTMLElement("video")}} ditanamkan sehingga kita dapat memanipulasi sebuah konten multimedia.
-
"Forms" pada HTML5
-
Perbaikan pada form di HTML5: the constraint validation API, beberapa attribute baru, nilai baru untuk {{HTMLElement("input")}} atribut {{htmlattrxref("type", "input")}} dan elemen baru yaitu {{HTMLElement("output")}}.
-
Elemen-elemen baru Semantik
-
Disamping section, media dan form elements, there are numerous new elements, like {{HTMLElement("mark")}}, {{HTMLElement("figure")}}, {{HTMLElement("figcaption")}}, {{HTMLElement("data")}}, {{HTMLElement("time")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, or {{HTMLElement("meter")}} and {{HTMLElement("main")}}, increasing the amount of valid HTML5 elements.
-
Perbaikan pada {{HTMLElement("iframe")}}
-
Using the {{htmlattrxref("sandbox", "iframe")}}, {{htmlattrxref("seamless", "iframe")}}, and {{htmlattrxref("srcdoc", "iframe")}} attributes, authors can now be precise about the level of security and the wished rendering of an {{HTMLElement("iframe")}} element.
-
MathML
-
Allows directly embedding mathematical formulas.
-
Introduction to HTML5
-
This article introduces how to indicate to the problem that you are using HTML5 in your web design or web application.
-
HTML5-compliant parser
-
The parser, which turns the bytes of an HTML document into a DOM, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid HTML. This leads to far greater predictability and interoperability between HTML5-compliant browsers.
-
- -

Connectivity

- -
-
Web Sockets
-
Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means.
-
Server-sent events
-
Allows a server to push events to a client, rather than the classical paradigm where the server could send data only in response to a client's request.
-
WebRTC
-
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
-
- -

Offline & storage

- -
-
Offline resources: the application cache
-
Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level.
-
Online and offline events
-
Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.
-
WHATWG client-side session and persistent storage (aka DOM Storage)
-
Client-side session and persistent storage allows web applications to store structured data on the client side.
-
IndexedDB
-
IndexedDB is a web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes.
-
Using files from web applications
-
Support for the new HTML5 File API has been added to Gecko, making it possible for web applications to access local files selected by the user. This includes support for selecting multiple files using the {{HTMLElement("input")}} of type file HTML element's new multiple attribute. There also is FileReader.
-
- -

Multimedia

- -
-
Using HTML5 audio and video
-
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
-
WebRTC
-
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
-
Using the Camera API
-
Allows using, manipulating, and storing an image from the computer's camera.
-
Track and WebVTT
-
The {{HTMLElement("track")}} element allows subtitles and chapters. WebVTT is a text track format.
-
- -

3D, graphics & effects

- -
-
Canvas Tutorial
-
Learn about the new {{HTMLElement("canvas")}} element and how to draw graphs and other objects in Firefox.
-
HTML5 text API for <canvas> elements
-
The HTML5 text API is now supported by {{HTMLElement("canvas")}} elements.
-
WebGL
-
WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 {{HTMLElement("canvas")}} elements.
-
SVG
-
An XML-based format of vectorial images that can directly be embedded in the HTML.
-
 
-
-
- -
-

Performance & integration

- -
-
Web Workers
-
Allows delegation of JavaScript evaluation to background threads, allowing these activities to prevent slowing down interactive events.
-
XMLHttpRequest Level 2
-
Allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. This is the technology behind Ajax.
-
JIT-compiling JavaScript engines
-
The new generation of JavaScript engines is much more powerful, leading to greater performance.
-
History API
-
Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information.
-
The contentEditable attribute: transform your website to a wiki!
-
HTML5 has standardized the contentEditable attribute. Learn more about this feature.
-
Drag and drop
-
The HTML5 drag and drop API allows support for dragging and dropping items within and between web sites. This also provides a simpler API for use by extensions and Mozilla-based applications.
-
Focus management in HTML
-
The new HTML5 activeElement and hasFocus attributes are supported.
-
Web-based protocol handlers
-
You can now register web applications as protocol handlers using the navigator.registerProtocolHandler() method.
-
requestAnimationFrame
-
Allows control of animations rendering to obtain optimal performance.
-
Fullscreen API
-
Controls the usage of the whole screen for a Web page or application, without the browser UI displayed.
-
Pointer Lock API
-
Allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit.
-
Online and offline events
-
In order to build a good offline-capable web application, you need to know when your application is actually offline. Incidentally, you also need to know when your application has returned to an online status again.
-
- -

Device access

- -
-
Using the Camera API
-
Allows using, manipulating, and storing an image from the computer's camera.
-
Touch events
-
Handlers to react to events created by a user pressing touch screens.
-
Using geolocation
-
Let browsers locate the position of the user using geolocation.
-
Detecting device orientation
-
Get the information when the device on which the browser runs changes orientation. This can be used as an input device (e.g., to make games that react to the position of the device) or to adapt the layout of a page to the orientation of the screen (portrait or landscape).
-
Pointer Lock API
-
Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.
-
- -

Styling

- -

CSS has been extended to be able to style elements in a much more complex way. This is often referred as CSS3, though CSS is not a monolithic specification any more and the different modules are not all at level 3: some are at level 1 and others at level 4, with all the intermediate levels covered.

- -
-
New background styling features
-
It is now possible to put a shadow to a box, using {{cssxref("box-shadow")}} and multiple backgrounds can be set.
-
More fancy borders
-
Not only it is now possible to use images to style borders, using {{cssxref("border-image")}} and its associated longhand properties, but rounded borders are supported via the {{cssxref("border-radius")}} property.
-
Animating your style
-
Using CSS Transitions to animate between different states or using CSS Animations to animate parts of the page without a triggering event, you can now control mobile elements on your page.
-
Typography improvement
-
Authors have better control to reach better typography. They can control {{cssxref("text-overflow")}} and hyphenation, but also can add a shadow to it or control more precisely its decorations. Custom typefaces can be downloaded and applied thanks to the new {{cssxref("@font-face")}} at-rule.
-
New presentational layouts
-
In order to improve the flexibility of designs, two new layouts have been added: the CSS multi-column layout, and the CSS flexible box layout.
-
-
-
- -

External References
-
- Html5 Tutorial
-  

- -

 

diff --git a/files/id/web/guide/index.html b/files/id/web/guide/index.html deleted file mode 100644 index 5e7889fa77..0000000000 --- a/files/id/web/guide/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: Paduan Pengembang Web -slug: Web/Guide -tags: - - Landing - - Paduan - - TopicStub - - Web -translation_of: Web/Guide ---- -

Artikel ini memberikan informasi untuk membantu anda menggunakan teknologi dan API secara spesifik.

- -
-
-
-
Area Belajar HTML
-
HyperText Markup Language (HTML) merupakan inti bahasa untuk hampir semua konten Web. Hampir keseluruhan yang anda lihat di layar browser, pada dasarnya, menggunakan HTML.
-
Area Belajar CSS
-
Cascading Style Sheets (CSS) adalah bahasa stylesheet yang digunakan untuk mendeskripsikan tampilan dokumen yang ditulis di HTML.
-
Paduan pegembang Event
-
Events mengacu baik pada pola desain yang digunakan untuk penanganan secara asynchronous pada berbagai peristiwa di halaman web dan penamaan, karakterisasi, dan penggunaan sejumlah besar peristiwa dari berbagai tipe.
-
Grafis di Web
-
Website modern dan aplikasi sering memerlukan menyajikan grafis dari berbagai kecanggihan.
-
Paduan Web API
-
Daftar semua Web API dan apa yang dihasilkan.
-
JavaScript
-
JavaScript adalah bahasa scripting yang ampuh digunakan untuk membuat aplikasi Web.
-
Lokalisasi dan pengkodean karakter
-
Browser memproses teks sebagai Unicode secara internal. Namun, cara merepresentasikan karakter dalam bentuk bytes (character encoding) yang digunakan untuk mengirim teks melalui jaringan ke browser.  Spesifikasi HTML menyarankan penggunaan UTF-8 encoding (dimana mewakili semua Unicode), dan terlepas dari pengkode-an yang digunakan, dibutuhkan konten Web untuk mendeklarasikan pengkode-an tersebut.
-
Pengembangan Mobile Web
-
Halaman ini memberikan gambaran dari beberapa teknik utama yang dibutuhkan desain Website sehingga berjalan dengan baik di perangkat mobile. Jika anda mencari informasi di proyek Mozilla's Firefox OS, lihat halaman Firefox OS. Atau anda mungkin tertarik pada detail tentang Firefox for Android.
-
-
- -
-
-
Optimasi dan kinerja
-
Ketika membangun modern Web apps dan situs, sangat penting untuk membuat konten yang bekerja dengan cepat dan efisien. Ini memungkinkan situs bekerja dengan baik pada keduanya, sistem Desktop yang kuat dan perngkat genggam yang lemah.
-
Parsing and serializing XML
-
Platform Web menyediakan metode yang berbeda dari parsing and serializing XML, dengan masing-masing pro dan kontra.
-
Open Web Font Format (WOFF)
-
WOFF (Web Open Font Format) adalah file format font yang gratis untuk semua pengguna di web.
-
Menggunakan Objek FormData
-
Objek FormData memungkinkan anda menkompilasi serangkaian key/value pairs untuk dikirim menggunakan XMLHttpRequest. Utamanya ditujukan untuk mengirim format data, namun dapat digunakan secara terpisah dari format dengan tujuan untuk mengirim keyed data. Pengiriman dengan format yang sama dengan bentuk method submit() digunakan untuk mengirim data jika bentuk tipe encoding ditetapkan ke "multipart/form-data".
-
Glosarium
-
Menjelaskan berbagai istilah teknis terkait Web dan Internet.
-
-
-
- -

Lihat Juga

- - diff --git a/files/id/web/html/element/base/index.html b/files/id/web/html/element/base/index.html deleted file mode 100644 index 6b4a556381..0000000000 --- a/files/id/web/html/element/base/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: -slug: Web/HTML/Element/base -translation_of: Web/HTML/Element/base ---- -

{{HTMLRef}}

- -

The HTML <base> element specifies the base URL to use for all relative URLs contained within a document. There can be only one <base> element in a document. 

- -

The base URL of a document can be queried from a script using {{domxref('document.baseURI')}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content categoriesMetadata content.
Permitted contentNone, it is an {{Glossary("empty element")}}.
Tag omissionThere must be no closing tag.
Permitted parentsAny {{HTMLElement("head")}} that doesn't contain any other {{HTMLElement("base")}} element
Permitted ARIA rolesNone
DOM interface{{domxref("HTMLBaseElement")}}
- -

Attributes

- -

This element's attributes include the global attributes.

- -
-
{{htmlattrdef("href")}}
-
The base URL to be used throughout the document for relative URL addresses. If this attribute is specified, this element must come before any other elements with attributes whose values are URLs. Absolute and relative URLs are allowed.
-
{{htmlattrdef("target")}}
-
A name or keyword indicating the default location to display the result when hyperlinks or forms cause navigation, for elements that do not have an explicit target reference. It is a name of, or keyword for, a browsing context (for example: tab, window, or inline frame). The following keywords have special meanings: -
    -
  • _self: Load the result into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • -
  • _blank: Load the result into a new unnamed browsing context.
  • -
  • _parent: Load the result into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
  • -
  • _top: Load the result into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.
  • -
-
-
- -

Usage notes

- -

If multiple <base> elements are specified, only the first href and first target value are used; all others are ignored.

- -

Examples

- -
<base href="http://www.example.com/page.html">
-<base target="_blank" href="http://www.example.com/page.html">
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'semantics.html#the-base-element', '<base>')}}{{Spec2('HTML WHATWG')}}No change since last snapshot.
{{SpecName('HTML5 W3C', 'document-metadata#the-base-element', '<base>')}}{{Spec2('HTML5 W3C')}}Specified the behavior of target
{{SpecName('HTML4.01', 'struct/links.html#h-12.4', '<base>')}}{{Spec2('HTML4.01')}}Added the target attribute
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}} [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Support of relative URIs for href was added in Gecko 2.0 (Firefox 4.0)

- -

[2] Before Internet Explorer 7, <base> could be positioned anywhere in the document and the nearest value of <base> was used. Support for relative URLs has been removed in Internet Explorer 8

diff --git a/files/id/web/html/element/dialog/index.html b/files/id/web/html/element/dialog/index.html deleted file mode 100644 index ac51fecd40..0000000000 --- a/files/id/web/html/element/dialog/index.html +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: ': The Dialog element' -slug: Web/HTML/Element/dialog -translation_of: Web/HTML/Element/dialog ---- -

Elemen <dialog> menampilkan sebuah kotak dialog atau komponen interaktif lainnya seperti halnya inspektor atau jendela.

- -

 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Kategori kontenAlur Konten, bagian akar
Konten yang diijinkanAlur konten
Penanda kesalahan{{no_tag_omission}}
Tingkatan yang diijinkanSetiap elemen yang menerima alur konten
Peran Aria yang diijinkan{{ARIARole("alertdialog")}}
Antarmuka DOM{{domxref("HTMLDialogElement")}}
- -

Atribut

- -

Elemen ini memiliki atribut global. Penggunaan atribut tabindex harus dihindari pada elemen <dialog> .

- -
-
{{htmlattrdef("open")}}
-
Menandakan bahwa dialog telah aktif dan dapat digunakan. Ketika atribut open belum diatur, maka dialog tidak akan tampil kepada pengguna.
-
- -

Catatan penggunaan

- -

 

- - - -

Contoh

- -

Contoh sederhana

- -
<dialog open>
-  <p>Greetings, one and all!</p>
-</dialog>
-
- -

Contoh lanjutan

- -

Pada contoh ini akan terbuka kotak dialog saat tombol "Update details" diklik.

- -

HTML

- -
<!-- Simple pop-up dialog box, containing a form -->
-<dialog open id="favDialog">
-  <form method="dialog">
-    <section>
-      <p><label for="favAnimal">Favorite animal:</label>
-      <select id="favAnimal">
-        <option></option>
-        <option>Brine shrimp</option>
-        <option>Red panda</option>
-        <option>Spider monkey</option>
-      </select></p>
-    </section>
-    <menu>
-      <button id="cancel" type="reset">Cancel</button>
-      <button type="submit">Confirm</button>
-    </menu>
-  </form>
-</dialog>
-
-<menu>
-  <button id="updateDetails">Update details</button>
-</menu>
-
- -

JavaScript

- -
(function() {
-  var updateButton = document.getElementById('updateDetails');
-  var cancelButton = document.getElementById('cancel');
-  var favDialog = document.getElementById('favDialog');
-
-  // Update button opens a modal dialog
-  updateButton.addEventListener('click', function() {
-    favDialog.showModal();
-  });
-
-  // Form cancel button closes the dialog box
-  cancelButton.addEventListener('click', function() {
-    favDialog.close();
-  });
-})();
-
- -

Hasil

- -

{{EmbedLiveSample("Contoh_lanjutan", "100%", 300)}}

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKeterangan
{{SpecName('HTML WHATWG', 'forms.html#the-dialog-element', '<dialog>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.2', 'interactive-elements.html#the-dialog-element', '<dialog>')}}{{Spec2('HTML5.2')}}Initial definition
- -

Kompatibilitas browser

- - - -

{{Compat("html.elements.dialog")}}

- -

Polyfills

- -

Sertakan polyfill ini untuk menyediakan dukungan terhadap browser lawas

- -

dialog-polyfill

- -

Lihat juga

- - - -
{{HTMLRef}}
diff --git a/files/id/web/html/element/image/index.html b/files/id/web/html/element/image/index.html deleted file mode 100644 index 047ac8f8b4..0000000000 --- a/files/id/web/html/element/image/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: -slug: Web/HTML/Element/image -translation_of: Web/HTML/Element/image ---- -
{{non-standard_header}}
- -

Ringkasan

- -

Elemen HTML <image> adalah elemen eksperimental yang dirancang untuk menampilkan gambar. Ini tidak pernah di implementasikan dan standar elemen {{HTMLElement ("img")}} harus digunakan.

- -
-

Jangan Gunakan! Untuk menampilkan gambar, gunakan standar elemen {{HTMLElement ("img")}} .

-
- -

Catatan sampai Firefox 22, meskipun tidak didukung, elemen <image> diasosiasikan dengan {{domxref ("HTMLSpanElement")}}. Kemudian diperbaiki dan sekarang diasosiasikan dengan {{domxref ("HTMLElement")}} mengikuti spesifikasi yang diminta.

diff --git a/files/id/web/html/element/index.html b/files/id/web/html/element/index.html deleted file mode 100644 index 6651addc38..0000000000 --- a/files/id/web/html/element/index.html +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: HTML element reference -slug: Web/HTML/Element -tags: - - Elemen - - HTML - - Referensi - - Web - - dasar -translation_of: Web/HTML/Element ---- -
{{HTMLSidebar("Elements")}}
- -

Halaman ini menampilkan semua daftar {{Glossary("HTML")}} {{Glossary("Element","elements")}}, yang dibuat menggunakan {{Glossary("Tag", "tags")}}. Ini dikelompokkan berdasarkan fungsi untuk membantu Anda mengingat lebih mudah. Daftar abjad semua element tersedia di sidebar pada setiap halaman element seperti yang ini.

- -
-

Untuk informasi lebih tentang dasar-dasar element HTML dan attribut, lihat artikel bagian pengenalan HTML.

-
- -

Akar Utama

- -

{{HTMLRefTable("HTML Root Element")}}

- -

Document metadata

- -

Metadata mengandung informasi halaman. Ini terdapat informasi tentang styles, scripts dan data untuk membantu perangkat lunak ({{Glossary("search engine", "search engines")}}, {{Glossary("Browser","browsers")}}, dsb.) gunakan dan alihkan halaman. Metadata untuk style dan script bisa didefinisikan di halaman atau link untuk berkas lainnya yabg memiliki informasinya.

- -

{{HTMLRefTable("HTML Document Metadata")}}

- -

Bagian Dasar

- -

{{HTMLRefTable("Sectioning Root Element")}}

- -

Kontent Bagian

- -

Element konten bagian memungkinkan Ansa mengatur konten dokumen menjadi kepingan-kepingan logis. Gunakan element bagian untuk membuat sebagian besar konten halaman Anda, termasuk navigasi header dan footer, dan judul element untuk mengidentifikasi bagian kontent.

- -

{{HTMLRefTable("HTML Sections")}}

- -

Konten kalimat

- -

Kegunaan element teks konten HTML mengatur blok atau bagian konten yang ditempatkan antara tag pembuka {{HTMLElement("body")}} dan penutup </body> . Penting untuk {{Glossary("accessibility")}} and {{Glossary("SEO")}}, element-element ini mengenali tujuan atau struktur kontennya.

- -

{{HTMLRefTable("HTML Grouping Content")}}

- -

Teks semantik dalam baris

- -

Kegunaan teks semantik dalam baris HTML untuk memberikan tujuan, struktur, atau gaya kata, baris, atau potongan kata sembarang.

- -

{{HTMLRefTable("HTML Text-Level Semantics")}}

- -

Gambar dan multimedia

- -

HTML mendukung beragam sumber multimedia seperti gambar, audio, dan vidio.

- -

{{HTMLRefTable("multimedia")}}

- -

Embedded content

- -

Selain konten multimedia biasa, HTML dapat menyertakan konten lainnya, walaupun tidak selalu mudah menyertakannya.

- -

{{HTMLRefTable({"include":["HTML embedded content"], "exclude":["multimedia"]})}}

- -

Scripting

- -

Untuk membuat konten dinamis dan aplikasi web, HTML mendukung penggunaan bahasa skripsi, secara paling jelas JavaScript. Element tertentu mendukung kemampuan ini.

- -

{{HTMLRefTable("HTML Scripting")}}

- -

Batas Pengubahan

- -

Element ini memungkinkan Anda menyediakan indikasi bagian spesifik bagian kalimat yang telah diubah.

- -

{{HTMLRefTable("HTML Edits")}}

- -

Konten tabel

- -

Element ini digunakan untuk membuat dan menangani data tabular.

- -

{{HTMLRefTable("HTML tabular data")}}

- -

Formulir

- -

HTML menyediakan beberapa element yang dapat digunakan bersama untuk membuat formulir, dimana pengguna dapat mengisi dan memasukan ke situs web atau aplikasi. Terdapat banyak informasi ini tersedia di panduan formulir HTML.

- -

{{HTMLRefTable({"include": ["HTML forms"], "exclude":["Deprecated"]})}}

- -

Element interaktif

- -

HTML menawarkan pilihan element yang membantu untuk membuat pengguna interaktif berhadapan dengan objek.

- -

{{HTMLRefTable("HTML interactive elements")}}

- -

Komponen Web

- -

Komponen Web adalah teknologi HTML terhubung yang memungkinkan untuk, secara inti, membuat dan menggunakan element khusus seperti itu HTML umum. Selain itu, Anda dapat membuat versi khusus element HTML standar.

- -

{{HTMLRefTable({"include":["Web Components"],"elements":["shadow"]})}}

- -

Element Usang dan Dihilangkan

- -
-

Peringatan: Ini adalah element HTML lama yang dihilangkan dan seharusnya tidak digunakan. Anda harus tidak pernah menggunakannya pada proyek baru, dan harus mengubahnya pada proyek lama secepat yang Anda bisa. Berikut ini adalah daftarnya, hanya untuk informasi saja.

-
- -

{{HTMLRefTable({"include":["Deprecated","Obsolete"]})}}

diff --git a/files/id/web/html/index.html b/files/id/web/html/index.html deleted file mode 100644 index 11a63d028d..0000000000 --- a/files/id/web/html/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: HTML -slug: Web/HTML -translation_of: Web/HTML ---- -
{{HTMLSidebar}}
- -

HTML (HyperText Markup Language) merupakan building block web paling dasar. Ini memberikan arti dan struktur konten web. Teknologi-teknologi lainnya disamping HTML umumnya digunakan untuk menggambarkan penampilan/gambaran (CSS) atau fungsionalitas/tingkah laku (JavaScript).

- -

"Hypertext" merujuk ke link yang menghubungkan halaman web satu dengan lainnya, baik dalam satu situs maupun antar situs web. Dengan mengunggah konten ke internet dan menghubungkannya ke halaman yang dibuat oleh orang lain, Anda menjadi pertisipasi aktif di World Wide Web.

- -

HTML menggunakan "markup" untuk anotasi teks, gambar, dan konten lainnya untuk ditampilkan dalam peramban Web. Markip HTML terdapat "elements" khusus seperti {{HTMLElement("head")}}, {{HTMLElement("title")}}, {{HTMLElement("body")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("p")}}, {{HTMLElement("div")}}, {{HTMLElement("span")}}, {{HTMLElement("img")}}, {{HTMLElement("aside")}}, {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("datalist")}}, {{HTMLElement("details")}}, {{HTMLElement("embed")}}, {{HTMLElement("nav")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("video")}}, {{HTMLElement("ul")}}, {{HTMLElement("ol")}}, {{HTMLElement("li")}} dan masih banyak lagi.

- -

Elemen HTML dibedakan dari teks lain dalam dokumen dengan "tags", yang terdiri dari nama elemen yang dikelilingi oleh "<" dan ">". Nama elemen dalam tag itu insensitif. Yakni, dapat ditulis dengan huruf besar, huruf kecil, atau gabungan. Contohnya tag <title> dapat ditulis sebagai <Title>, <TITLE>, atau dengan cara lainnya.

- -

Artikel-artikel dibawah dalat membantu Amda belajar lebih banyak tentang HTML.

- -
-
    -
  • Pengenalan HTML - -

    Jika kamu baru di pengembangan Web, pastima untum membaca artikel Dasar-dasar HTML kami untuk belajar apa HTML itu dan cara menggunakannya.

    -
  • -
  • Tutorial HTML -

    Untuk artikel tentang cara menggunakan HTML, tutorial yang bagus dan dipenuhi contoh, periksa artikel Ruang Belajar HTML.

    -
  • -
  • Referensi HTML -

    Di bagian Referensi HTML yang luas, Anda akan menemukan setiap detail elemen dan attribut dalam HTML.

    -
  • -
- -
-
-

Tutorial Pemula

- -

Fitur-fitur modul ganda Ruang Belajar HTML yang mengajari HTML dari bawah ke atas — tanpa dibutuhkan pengetahuan sebelumnya.

- -
-
Pengenalan pada HTML
-
Tahap kumpulan modul ini, membuat Anda terbiasa menggunakan konsep dan sintaks penting seperti melihat pengaplikasian HTML pada teks, cara untuk membuat hyperlink, dan cara menggunakan HTML untuk struktur halaman web.
-
Multimedia and embedding
-
This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages.
-
Tabel-tabel HTML
-
Mewakili data tabular di halaman web yang dapat dimengerti, cara keaksesan dapat menantang. Modul ini mencangkup markup dasar tabel, bersama dengan fitur lebih  kompleks seperti keterangan implementasi dan ringkasan.
-
Formulir HTML
-
Formulir merupakan bagian sangat penting di Web — ini menyediakan banyak kegunaan yang Anda butuhkan untuk berinteraksi dengan situs-situs web, msl. pendaftaran dan masuk, pengiriman masukan, pembelian produk, dan lainnya. Modul ini membantu Anda dengan membuat formulir sisi klien/bagian awal hingga akhir.
-
Pakai HTML untuk memperbaiki kesalahan umum.
-
Menyediakan link ke bagian-bagian konten menjelaskan cara menggubakan HTML untuk menyelesaikan masalah sangat umum ketika membuat halaman web: mengatur judul, menambahkan gambar atau vidio, penekanan konten, pembuatan formulir dasar, dsb.
-
- -

Topik Lanjut

- -
-
Gambar diaktifkan CORS
-
Attribut {{htmlattrxref("crossorigin", "img")}}, di kombinasikan dengan bagian kepala {{glossary("CORS")}} yang sesuai, memungkinkan gambar didefinisikan dengan elemen {{HTMLElement("img")}} untuk dimuat dari origin asing dan digunakan di elemen {{HTMLElement("canvas")}} seolah sedang dimuat dari asal saat ini.
-
CORS mengatur atribut
-
Beberapa elemen HTML mendukung CORS, seperti {{HTMLElement("img")}} atau {{HTMLElement("video")}}, memiliki atribut crossorigin (properti crossOrigin), yang memungkinkan Anda mengkonfigurasikan permintaan CORS untuk mengambil data elemen.
-
Fokus manajemen di HTML
-
Metode Atribut DOM activeElement dan DOM hasFocus() membantu Anda melacak dan mengendalikan interaksi pengguna dengan elemen di halaman web.
-
Mem-preloading konten dengan rel="preload"
-
The preload value of the {{htmlelement("link")}} element's {{htmlattrxref("rel", "link")}} attribute allows you to write declarative fetch requests in your HTML {{htmlelement("head")}}, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements. This article provides a basic guide to how preload works.
-
-
- -
-

Referensi

- -
-
Refensi HTML
-
HTML terdiri dari elemen, setiap elemen mugkin dimofikasi dengan beberapa atribut. Dokumen HTML terhubung satu sama lain dengan link.
-
Referensi elemen HTML
-
Kunjungi semua daftar {{glossary("HTML")}} {{glossary("Element", "elements")}}.
-
Referensi atribut HTML
-
Elemen HTML memiliki atribut. Ini adalah nilai tambahan yang mengkonfigurasikan elemen atau menyesuaikan tingkah lakunya di berbagai cara.
-
Atribut Global
-
Global attributes may be specified on all HTML elements, even those not specified in the standard. This means that any non-standard elements must still permit these attributes, even though those elements make the document HTML5-noncompliant.
-
Inline elements and block-level elements
-
Elemen HTML elements biasanya elemen "inline" atau "block-level". Inline elemen hanya menempati ruang yang terikat dengan elemen yang didefinisikan. Block-level menempati seluruh ruang elemen orang tuanya (parent element) (container), dengan demikian membuat sebuah "block."
-
Jenis-jenis Link
-
Di HTML, beragam jenis link dapat digunakan untuk membangun dan mendefinisikan hubungan antara dua dokumen. Elemen link yang jenisnya dapat diatur ke dalam {{HTMLElement("a")}}, {{HTMLElement("area")}} dan {{HTMLElement("link")}}.
-
Panduan jenis-jenis media dan format pada web
-
Elemen {{HTMLElement("audio")}} dan {{HTMLElement("video")}} memungkinkan Anda memutar media audio dan vidio secara langsung di konten Anda tidan perlu dukungan perangkat lunak tambahan.
-
Jenis-jenis konten HTML
-
HTML is comprised of several kinds of content, each of which is allowed to be used in certain contexts and is disallowed in others. Similarly, each has a set of other content categories they can contain and elements which can or can't be used in them. This is a guide to these categories.
-
Quirks mode and standards mode
-
Historical information on quirks mode and standards mode.
-
- -

Topik-topik berhubungan

- -
-
Mengaplikasikan warna ke elemen HTML menggunakan CSS
-
Artikel ini mencakup sebagian besar cara Anda menggunakan CSS untuk memberikan warna pada konten HTML, daftar bagian dokumen apa yang dapat diwarnai dan properti CSS yang digunakan untuk melakukannya. Termasuk contoh, peralatan tempat palet, dan lainnya.
-
-
-
-Lihat semua...
diff --git a/files/id/web/http/basics_of_http/index.html b/files/id/web/http/basics_of_http/index.html deleted file mode 100644 index a00d7fe410..0000000000 --- a/files/id/web/http/basics_of_http/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Basics of HTTP -slug: Web/HTTP/Basics_of_HTTP -tags: - - Guide - - HTTP - - NeedsTranslation - - Overview - - TopicStub -translation_of: Web/HTTP/Basics_of_HTTP ---- -
{{HTTPSidebar}}
- -

HTTP adalah sebuah protokol yang dapat diperluas. HTTP bergantung pada beberapa konsep dasar seperti the notion of resources and URIs, a simple structure of messages, and a client-server structure for the communication flow. On top of these basic concepts, numerous extensions have appeared over the years, adding new functionality and new semantics by creating new HTTP methods or headers.

- -

Articles

- -
-
Overview of HTTP
-
Describes what HTTP is and its role in the Web architecture, its position in the protocol stack.
-
Evolution of HTTP
-
HTTP was created in the early 1990s and has been extended several times. This article goes through its history and describes HTTP/0.9, HTTP/1.0, HTTP/1.1, and the modern HTTP/2 as well as minor novelties introduced over the years.
-
Negotiating an HTTP version
-
Explains how a client and a server can negotiate a specific HTTP version and eventually upgrade the protocol version used.
-
Resources and URIs
-
A brief introduction of the notion of resources, identifiers, and locations on the Web.
-
Identifying resources on the Web
-
Describes how Web resources are referenced and how to locate them.
-
Data URIs
-
A specific kind of URIs that directly embeds the resource it represents. Data URIs are very convenient, but have some caveats.
-
Resource URLs {{Non-standard_Inline}}
-
Resource URLs, URLs prefixed with the resource: scheme, are used by Firefox and Firefox browser extensions to load resources internally, but some of the information is available to sites the browser connects to as well.
-
Separating identity and location of a resource: the Alt-Svc HTTP header
-
Most of the time identity and location of a Web resource are shared, this can be changed with the {{HTTPHeader("Alt-Svc")}} header.
-
MIME types
-
Since HTTP/1.0, different types of content can be transmitted. This article explains how this is done using the {{HTTPHeader("Content-Type")}} header and the MIME standard.
-
Choosing between www and non-www URLs
-
Advice on using a www-prefixed domain or not, this article explains the consequences of the choice as well as how to make it.
-
Flow of an HTTP session
-
This fundamental article describes a typical HTTP session: what happens under the hood when you click on a link in your browser…
-
HTTP Messages
-
HTTP Messages transmitted during requests or responses have a very clear structure; this introductory article describes this structure, its purpose and its possibilities.
-
Frame and message structure in HTTP/2
-
HTTP/2 encapsulates and represents HTTP/1.x messages in a binary frame. This article explains the frame structure, its purpose and the way it is encoded.
-
Connection management in HTTP/1.x
-
HTTP/1.1 was the first version of HTTP to support persistent connection and pipelining. This article explains these two concepts.
-
Connection management in HTTP/2
-
HTTP/2 completely revisited how connections are created and maintained: this article explains how HTTP frames allow multiplexing and solve the 'head-of-line' blocking problem of former HTTP versions.
-
Content Negotiation
-
HTTP introduces a set of headers, starting with Accept- as a way for a browser to announce the format, language, or encoding it prefers. This article explains how this advertisement happens, how the server is expected to react and how it will choose the most adequate response.
-
diff --git a/files/id/web/http/index.html b/files/id/web/http/index.html deleted file mode 100644 index 3e2144fb57..0000000000 --- a/files/id/web/http/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: HTTP -slug: Web/HTTP -tags: - - HTTP - - Referensi - - Web -translation_of: Web/HTTP ---- -
{{HTTPSidebar}}
- -

Hypertext Transfer Protocol (HTTP) adalah sebuah protokol lapisan-aplikasi untuk mentransmisi dokumen hypermedia, seperti HTML. Ini dirancang untuk komunikasi antara peramban web dan server web, meskipun bisa digunakan untuk keperluan lain juga. Ini mengikuti sebuah model klien-server klasik, dengan sebuah klien membuka sebuah koneksi, membuat sebuah permintaan (request), dan menunggu hingga mendapatkan sebuah respon. Ini juga sebuah protokol tanpa-keadaan, maksudnya server tidak menyimpan data (keadaan) antara kedua permintaan. Meskipun kadang berdasarkan pada sebuah lapisan TCP/IP, bisa digunakan pada lapisan transport andal apa saja;  berarti sebuah protokol tidak kehilangan pesan secara diam-diam, seperti UDP.

- -
-
-

Tutorial

- -

Belajar bagaimana untuk menggunakan HTTP dengan panduan dan tutorial.

- -
-
Ikhtisan dari HTTP
-
Fitur dasar dari protokol klien-server: apa yang bisa digunakan dan penggunaannya.
-
HTTP Cache
-
Caching sangat penting untuk mempercepat situs web. Artikel ini menjelaskan perbedaan metode dalam caching  dan bagaimana menggunakan HTTP Headers untuk mengendalikannya.
-
HTTP Kuki
-
Bagaimana kuki bekerja didefinisi oleh RFC 6265. Pada penerimaan sebuah permintaan HTTP, sebuah server bisa mengirim sebuah header Set-Cookie dengan responnya. Klien kemudian mengembalikan nilai kuki dengan setiap permintaan ke server yang sama dalam bentuk header permintaan Cookie. Kuki juga dapat ditetapkan untuk kadaluarsa pada tanggal tertentu, atau pembatasan pada domain dan jalur tertentu.
-
Cross-Origin Resource Sharing (CORS)
-
Permintaan Cross-site HTTP adalah permintaan HTTP untuk sumber daya dari domain lain kemduian domain dari sumberdaya membuat permintaan. Contohnya, sebuah laman HTML dari Domain A (http://domaina.example/), membuat sebuah permintaan untuk sebuah gambar pada Domain B (http://domainb.foo/image.jpg) malalui elemen img. Laman situs saat ini sangat biasa memuat sumber daya cross-site, termasuk CSS sytlesheets, gambar, skrip, dan sumber daya lainnya. CORS memungkinkan pengembang web untuk mengendaikan bagaimana situs mereka bereaksi kepada permintaan cross-site.
-
- -
-
Perkembangan dari HTTP
-
Sebuah deskripsi  dari perubahan antara HTTP veri awal, ke HTTP/2 moderen dan seterusnya.
-
Panduan keamanan situs Mozilla
-
Sebuah koleksi dari tip untuk membantu tim operasional dengan membuat aplikasi web yang aman.
-
Pesan HTTP (HTTP Messages)
-
Penjelasan tipe dan struktur dari berbagai jenis dan struktur dari HTTP/1.x dan HTTP/2.
-
Sebuah sesi HTTP yang khas
-
Menunjukan dan menjelaskan alur dari sebuah sesi HTTP biasa.
-
 
-
Manajemen koneksi pada HTTP/1.x
-
Menjelaskan tiga model manajemen koneksi yang tersedia pada HTTP/1.x, serta kelebihan dan kekurangan mereka.
-
-
- -
-

Referensi

- -

Jelajahi dokumentasi referensi HTTP yang terperinci.

- -
-
HTTP Headers
-
Pesan HTTP digunakan untuk menjelaskan secara tepat sumber daya atau perilaku dari server atau klien. header kepemilikan khusus bisa ditambahkan dengan menggunakan awalan X-; yang lain pada sebuah registri IANA, yang konten aslinya didefiniskan di RFC 4229. IANA juga mengelola registri dari usulan baru header pesan HTTP.
-
Metode Permintaan HTTP
-
Berbagai operasi yang bisa dilakukan dengan HTTP: {{HTTPMethod("GET")}}, {{HTTPMethod("POST")}}, tetapi juga permintaan yang kurang umum seperti {{HTTPMethod("OPTIONS")}}, {{HTTPMethod("DELETE")}} atau {{HTTPMethod("TRACE")}}.
-
Kode Status Respon HTTP
-
Kode respon HTTP menunjukan apakah permintaan HTTP tertentu berhasil diselesaikan. Respon dikelompokan dalam lima kelas: respon informasi, respon sukses, pengaihan, kesalahan klien, dan kealahan server.
-
Petunjuk CSP (CSP directives)
-
Bidang header respon {{HTTPHeader("Content-Security-Policy")}} memungkinkan administrator situs web untuk mengendalikan sumber daya user agent yang memungkinkan untuk dimuat pada halaman tertentu. Dengan beberapa pengecualian, sebagian besar kebijakan melibatkan penentuan asal server dan skrip titik-akhir (endpoints). 
-
- -

Alat & sumber daya

- -

Alat dan sumber daya yang berguna untuk memahami dan debugging HTTP.

- -
-
Firefox Developer Tools
-
Network monitor
-
Mozilla Observatory
-
-

Sebuah proyek yang dideain untuk membantu pengembang, administrator sistem, dan keamanan profesional mengkonfigurasi situs mereka secara aman.

-
-
RedBot
-
Alat untuk memeriksa header terkati-cache Anda.
-
Bagaimana Peramban Bekerja
-
Sebuah artikel yang sangat komprehensif tentang internal peramban dan alur permintaan melalui protokol HTTP. Sebuah artikel yang HARUS-DIBACA oleh tiap pengembang web.
-
- -

 

-
-
diff --git a/files/id/web/http/methods/get/index.html b/files/id/web/http/methods/get/index.html deleted file mode 100644 index ff8f8cdbab..0000000000 --- a/files/id/web/http/methods/get/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: GET -slug: Web/HTTP/Methods/GET -tags: - - HTTP - - Referensi - - Request method -translation_of: Web/HTTP/Methods/GET ---- -
{{HTTPSidebar}}
- -

Request HTTP GET method merupakan representasi dari resource spesifik. Request menggunakan GET hanya menerima data.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Request has bodyNo
Successful response has bodyYes
{{Glossary("Safe")}}Yes
{{Glossary("Idempotent")}}Yes
{{Glossary("Cacheable")}}Yes
Allowed in HTML formsYes
- -

Sintaks

- -
GET /index.html
-
- -

Spesifikasi

- - - - - - - - - - - - -
SpesifikasiJudul
{{RFC("7231", "GET", "4.3.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
- -

Kompabilitas Browser

- - - -

{{Compat("http.methods.GET")}}

- -

Lihat Juga

- - diff --git a/files/id/web/http/methods/index.html b/files/id/web/http/methods/index.html deleted file mode 100644 index 1045732cc2..0000000000 --- a/files/id/web/http/methods/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: HTTP request methods -slug: Web/HTTP/Methods -tags: - - HTTP - - Methods - - Reference - - TopicStub -translation_of: Web/HTTP/Methods ---- -
{{HTTPSidebar}}
- -
HTTP mendefinisikan seperangkat metode permintaan untuk menunjukkan tindakan yang diinginkan yang akan dilakukan untuk sumber daya tertentu. Meskipun mereka juga bisa menjadi kata benda, metode permintaan ini kadang-kadang disebut sebagai verba HTTP. Masing-masing menerapkan semantik yang berbeda, namun beberapa fitur umum digunakan bersama oleh mereka: mis. Metode permintaan dapat berupa {{glossary("safe")}}, {{glossary("idempotent")}}, atau {{glossary("cacheable")}}.
- -
 
- -
-
GET
-
Metode GET meminta representasi sumber daya yang ditentukan. Permintaan menggunakan GET seharusnya hanya mengambil data..
-
HEAD
-
Metode HEAD meminta tanggapan yang identik dengan permintaan GET, namun tanpa respon body.
-
POST
-
Metode POST digunakan untuk mengirimkan entitas ke sumber daya yang ditentukan, sering menyebabkan perubahan pada keadaan atau efek samping pada server.
-
PUT
-
-

Metode PUT menggantikan semua representasi terkini dari sumber target dengan muatan permintaan.

-
-
DELETE
-
Metode DELETE akan menghapus sumber daya yang ditentukan.
-
CONNECT
-
-

Metode CONNECT menetapkan terowongan ke server yang diidentifikasi oleh sumber target.

-
-
OPTIONS
-
Metode OPTIONS digunakan untuk menggambarkan opsi komunikasi untuk sumber target.
-
TRACE
-
-

Metode TRACE melakukan tes pesan loop-back di sepanjang jalan menuju sumber daya target.

-
-
PATCH
-
Metode PATCH digunakan untuk menerapkan modifikasi sebagian pada sumber daya.
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiJudulKomentar
{{RFC("7231", "Request methods", "4")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and ContentSpecifies GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE.
{{RFC("5789", "Patch method", "2")}}PATCH Method for HTTPSpecifies PATCH.
- -

Kompabilitas Browser

- - - -

{{Compat("http.methods")}}

- -

Lihat Juga

- - diff --git a/files/id/web/http/overview/index.html b/files/id/web/http/overview/index.html deleted file mode 100644 index 580166ef43..0000000000 --- a/files/id/web/http/overview/index.html +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: Gambaran HTTP -slug: Web/HTTP/Overview -translation_of: Web/HTTP/Overview -original_slug: Web/HTTP/Gambaran ---- -
{{HTTPSidebar}}
- -

HTTP adalah sebuah {{Glossary("protocol")}} yang memungkinkan pengambilan sumber daya, seperti dokumen HTML. Ini adalah dasar dari pertukaran data apa pun di Web dan itu adalah protokol client-server, yang berarti permintaan diprakarsai oleh penerima (Client), biasanya browser Web. Dokumen lengkap direkonstruksi dari berbagai sub-dokumen yang diambil, misalnya teks, deskripsi tata letak, gambar, video, skrip, dan banyak lagi.

- -

A Web document is the composition of different resources

- -

Client dan Server berkomunikasi dengan bertukar pesan individual (sebagai lawan aliran data). Pesan yang dikirim oleh Client, biasanya browser Web, disebut permintaan (requests) dan pesan yang dikirim oleh server sebagai jawaban disebut respons (responses)

- -

HTTP as an application layer protocol, on top of TCP (transport layer) and IP (network layer) and below the presentation layer.Dirancang pada awal 1990-an, HTTP adalah protokol yang dapat diperluas, yang telah berevolusi dari waktu ke waktu. Ini adalah lapisan aplikasi protokol yang dikirim melalui {{Glossary("TCP")}}, atau melalui koneksi TCP yang terenkripsi {{Glossary("TLS")}} meskipun begitu semua transportasi protokol yang terpercaya secara teori juga dapat digunakan. Karena sifatnya yang dapat diperluas, protokol ini digunakan tidak hanya untuk mengambil dokumen hiperteks, tetapi juga gambar dan video atau untuk memposting konten ke server, sama seperti hasil sebuah form HTML. HTTP juga dapat digunakan untuk mengambil bagian dokumen untuk memperbarui halaman Web sesuai permintaan.

- -

Components of HTTP-based systems

- -

HTTP is a client-server protocol: requests are sent by one entity, the user-agent (or a proxy on behalf of it). Most of the time the user-agent is a Web browser, but it can be anything, for example a robot that crawls the Web to populate and maintain a search engine index.

- -

Each individual request is sent to a server, which handles it and provides an answer, called the response. Between the client and the server there are numerous entities, collectively called {{Glossary("Proxy_server", "proxies")}}, which perform different operations and act as gateways or {{Glossary("Cache", "caches")}}, for example.

- -

Client server chain

- -

In reality, there are more computers between a browser and the server handling the request: there are routers, modems, and more. Thanks to the layered design of the Web, these are hidden in the network and transport layers. HTTP is on top, at the application layer. Although important to diagnose network problems, the underlying layers are mostly irrelevant to the description of HTTP.

- -

Client: the user-agent

- -

The user-agent is any tool that acts on the behalf of the user. This role is primarily performed by the Web browser; other possibilities are programs used by engineers and Web developers to debug their applications.

- -

The browser is always the entity initiating the request. It is never the server (though some mechanisms have been added over the years to simulate server-initiated messages).

- -

To present a Web page, the browser sends an original request to fetch the HTML document that represents the page. It then parses this file, making additional requests corresponding to execution scripts, layout information (CSS) to display, and sub-resources contained within the page (usually images and videos). The Web browser then mixes these resources to present to the user a complete document, the Web page. Scripts executed by the browser can fetch more resources in later phases and the browser updates the Web page accordingly.

- -

A Web page is a hypertext document. This means some parts of displayed text are links which can be activated (usually by a click of the mouse) to fetch a new Web page, allowing the user to direct their user-agent and navigate through the Web. The browser translates these directions in HTTP requests, and further interprets the HTTP responses to present the user with a clear response.

- -

The Web server

- -

On the opposite side of the communication channel, is the server, which serves the document as requested by the client. A server appears as only a single machine virtually: this is because it may actually be a collection of servers, sharing the load (load balancing) or a complex piece of software interrogating other computers (like cache, a DB server, or e-commerce servers), totally or partially generating the document on demand.

- -

A server is not necessarily a single machine, but several server software instances can be hosted on the same machine. With HTTP/1.1 and the {{HTTPHeader("Host")}} header, they may even share the same IP address.

- -

Proxies

- -

Between the Web browser and the server, numerous computers and machines relay the HTTP messages. Due to the layered structure of the Web stack, most of these operate at the transport, network or physical levels, becoming transparent at the HTTP layer and potentially making a significant impact on performance. Those operating at the application layers are generally called proxies. These can be transparent, forwarding on the requests they receive without altering them in any way, or non-transparent, in which case they will change the request in some way before passing it along to the server. Proxies may perform numerous functions:

- - - -

Basic aspects of HTTP

- -

HTTP is simple

- -

HTTP is generally designed to be simple and human readable, even with the added complexity introduced in HTTP/2 by encapsulating HTTP messages into frames. HTTP messages can be read and understood by humans, providing easier testing for developers, and reduced complexity for newcomers.

- -

HTTP is extensible

- -

Introduced in HTTP/1.0, HTTP headers make this protocol easy to extend and experiment with. New functionality can even be introduced by a simple agreement between a client and a server about a new header's semantics.

- -

HTTP is stateless, but not sessionless

- -

HTTP is stateless: there is no link between two requests being successively carried out on the same connection. This immediately has the prospect of being problematic for users attempting to interact with certain pages coherently, for example, using e-commerce shopping baskets. But while the core of HTTP itself is stateless, HTTP cookies allow the use of stateful sessions. Using header extensibility, HTTP Cookies are added to the workflow, allowing session creation on each HTTP request to share the same context, or the same state.

- -

HTTP and connections

- -

A connection is controlled at the transport layer, and therefore fundamentally out of scope for HTTP. Though HTTP doesn't require the underlying transport protocol to be connection-based; only requiring it to be reliable, or not lose messages (so at minimum presenting an error). Among the two most common transport protocols on the Internet, TCP is reliable and UDP isn't. HTTP therefore relies on the TCP standard, which is connection-based.

- -

Before a client and server can exchange an HTTP request/response pair, they must establish a TCP connection, a process which requires several round-trips. The default behavior of HTTP/1.0 is to open a separate TCP connection for each HTTP request/response pair. This is less efficient than sharing a single TCP connection when multiple requests are sent in close succession.

- -

In order to mitigate this flaw, HTTP/1.1 introduced pipelining (which proved difficult to implement) and persistent connections: the underlying TCP connection can be partially controlled using the {{HTTPHeader("Connection")}} header. HTTP/2 went a step further by multiplexing messages over a single connection, helping keep the connection warm and more efficient.

- -

Experiments are in progress to design a better transport protocol more suited to HTTP. For example, Google is experimenting with QUIC which builds on UDP to provide a more reliable and efficient transport protocol.

- -

What can be controlled by HTTP

- -

This extensible nature of HTTP has, over time, allowed for more control and functionality of the Web. Cache or authentication methods were functions handled early in HTTP history. The ability to relax the origin constraint, by contrast, has only been added in the 2010s.

- -

Here is a list of common features controllable with HTTP.

- - - -

HTTP flow

- -

When a client wants to communicate with a server, either the final server or an intermediate proxy, it performs the following steps:

- -
    -
  1. Open a TCP connection: The TCP connection is used to send a request, or several, and receive an answer. The client may open a new connection, reuse an existing connection, or open several TCP connections to the servers.
  2. -
  3. Send an HTTP message: HTTP messages (before HTTP/2) are human-readable. With HTTP/2, these simple messages are encapsulated in frames, making them impossible to read directly, but the principle remains the same. For example: -
    GET / HTTP/1.1
    -Host: developer.mozilla.org
    -Accept-Language: fr
    -
  4. -
  5. Read the response sent by the server, such as: -
    HTTP/1.1 200 OK
    -Date: Sat, 09 Oct 2010 14:28:02 GMT
    -Server: Apache
    -Last-Modified: Tue, 01 Dec 2009 20:18:22 GMT
    -ETag: "51142bc1-7449-479b075b2891b"
    -Accept-Ranges: bytes
    -Content-Length: 29769
    -Content-Type: text/html
    -
    -<!DOCTYPE html... (here comes the 29769 bytes of the requested web page)
    -
  6. -
  7. Close or reuse the connection for further requests.
  8. -
- -

If HTTP pipelining is activated, several requests can be sent without waiting for the first response to be fully received. HTTP pipelining has proven difficult to implement in existing networks, where old pieces of software coexist with modern versions. HTTP pipelining has been superseded in HTTP/2 with more robust multiplexing requests within a frame.

- -

HTTP Messages

- -

HTTP messages, as defined in HTTP/1.1 and earlier, are human-readable. In HTTP/2, these messages are embedded into a binary structure, a frame, allowing optimizations like compression of headers and multiplexing. Even if only part of the original HTTP message is sent in this version of HTTP, the semantics of each message is unchanged and the client reconstitutes (virtually) the original HTTP/1.1 request. It is therefore useful to comprehend HTTP/2 messages in the HTTP/1.1 format.

- -

There are two types of HTTP messages, requests and responses, each with its own format.

- -

Requests

- -

An example HTTP request:

- -

A basic HTTP request

- -

Requests consists of the following elements:

- - - -

Responses

- -

An example response:

- -

- -

Responses consist of the following elements:

- - - -

APIs based on HTTP

- -

The most commonly used API based on HTTP is the {{domxref("XMLHttpRequest")}} API, which can be used to exchange data between a {{Glossary("user agent")}} and a server. The modern {{domxref("Fetch API")}} provides the same features with a more powerful and flexible feature set.

- -

Another API, server-sent events, is a one-way service that allows a server to send events to the client, using HTTP as a transport mechanism. Using the {{domxref("EventSource")}} interface, the client opens a connection and establishes event handlers. The client browser automatically converts the messages that arrive on the HTTP stream into appropriate {{domxref("Event")}} objects, delivering them to the event handlers that have been registered for the events' {{domxref("Event.type", "type")}} if known, or to the {{domxref("EventSource.onmessage", "onmessage")}} event handler if no type-specific event handler was established.

- -

Conclusion

- -

HTTP is an extensible protocol that is easy to use. The client-server structure, combined with the ability to simply add headers, allows HTTP to advance along with the extended capabilities of the Web.

- -

Though HTTP/2 adds some complexity, by embedding HTTP messages in frames to improve performance, the basic structure of messages has stayed the same since HTTP/1.0. Session flow remains simple, allowing it to be investigated, and debugged with a simple HTTP message monitor.

diff --git a/files/id/web/http/proxy_servers_and_tunneling/index.html b/files/id/web/http/proxy_servers_and_tunneling/index.html deleted file mode 100644 index f035225649..0000000000 --- a/files/id/web/http/proxy_servers_and_tunneling/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Proxy servers and tunneling -slug: Web/HTTP/Proxy_servers_and_tunneling -tags: - - HTTP - - HTTP Tunneling - - NeedsTranslation - - Proxies - - Proxy - - TopicStub -translation_of: Web/HTTP/Proxy_servers_and_tunneling ---- -
{{HTTPSidebar}}
- -

When navigating through different networks of the Internet, proxy servers and HTTP tunnels are facilitating access to content on the World Wide Web. A proxy can be on the user's local computer, or anywhere between the user's computer and a destination server on the Internet. This page outlines some basics about proxies and introduces a few configuration options.

- -

There are two types of proxies: forward proxies (or tunnel, or gateway) and reverse proxies (used to control and protect access to a server for load-balancing, authentication, decryption or caching).

- -

Forward proxies

- -

A forward proxy, or gateway, or just "proxy" provides proxy services to a client or a group of clients. There are likely hundreds of thousands of open forward proxies on the Internet. They store and forward Internet services (like the DNS, or web pages) to reduce and control the bandwidth used by the group.

- -

Forward proxies can also be anonymous proxies and allow users to hide their IP address while browsing the Web or using other Internet services. TOR (The Onion Router), routes internet traffic through multiple proxies for anonymity.

- -

Reverse proxies

- -

As the name implies, a reverse proxy does the opposite of what a forward proxy does: A forward proxy acts on behalf of clients (or requesting hosts). Forward proxies can hide the identities of clients whereas reverse proxies can hide the identities of servers. Reverse proxies have several use cases, a few are:

- - - -

Forwarding client information through proxies

- -

Proxies can make requests appear as if they originated from the proxy's IP address. This can be useful if a proxy is used to provide client anonymity, but in other cases information from the original request is lost. The IP address of the original client is often used for debugging, statistics, or generating location-dependent content. A common way to disclose this information is by using the following HTTP headers:

- -

The standardized header:

- -
-
{{HTTPHeader("Forwarded")}}
-
Contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request.
-
- -

Or the de-facto standard versions:

- -
-
{{HTTPHeader("X-Forwarded-For")}} {{non-standard_inline}}
-
Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer.
-
{{HTTPHeader("X-Forwarded-Host")}} {{non-standard_inline}}
-
Identifies the original host requested that a client used to connect to your proxy or load balancer.
-
{{HTTPHeader("X-Forwarded-Proto")}} {{non-standard_inline}}
-
identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer.
-
- -

To provide information about the proxy itself (not about the client connecting to it), the Via header can be used.

- -
-
{{HTTPHeader("Via")}}
-
Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers.
-
- -

HTTP tunneling

- -

Tunneling transmits private network data and protocol information through public network by encapsulating the data. HTTP tunneling is using a protocol of higher level (HTTP) to transport a lower level protocol (TCP).

- -

The HTTP protocol specifies a request method called {{HTTPMethod("CONNECT")}}. It starts two-way communications with the requested resource and can be used to open a tunnel. This is how a client behind an HTTP proxy can access websites using SSL (i.e. HTTPS, port 443). Note, however, that not all proxy servers support the CONNECT method or limit it to port 443 only.

- -

See also the HTTP tunnel article on Wikipedia.

- -

Proxy Auto-Configuration (PAC)

- -

A Proxy Auto-Configuration (PAC) file is a JavaScript function that determines whether web browser requests (HTTP, HTTPS, and FTP) go directly to the destination or are forwarded to a web proxy server. The JavaScript function contained in the PAC file defines the function:

- -

The auto-config file should be saved to a file with a .pac filename extension:

- -
proxy.pac
- -

And the MIME type set to:

- -
application/x-ns-proxy-autoconfig
- -

The file consists of a function called FindProxyForURL. The example below will work in an environment where the internal DNS server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable:

- -
function FindProxyForURL(url, host) {
-  if (isResolvable(host))
-    return "DIRECT";
-  else
-    return "PROXY proxy.mydomain.com:8080";
-}
- -

See Proxy Auto-Configuration (PAC) for more examples.

- -

See also

- - diff --git a/files/id/web/http/proxy_servers_and_tunneling/proxy_auto-configuration_pac_file/index.html b/files/id/web/http/proxy_servers_and_tunneling/proxy_auto-configuration_pac_file/index.html deleted file mode 100644 index 340989a8d1..0000000000 --- a/files/id/web/http/proxy_servers_and_tunneling/proxy_auto-configuration_pac_file/index.html +++ /dev/null @@ -1,728 +0,0 @@ ---- -title: Proxy Auto-Configuration (PAC) file -slug: Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_PAC_file -translation_of: Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_(PAC)_file -original_slug: Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_(PAC)_file ---- -
{{HTTPSidebar}}
- -

File Proxy Auto-Configuration (PAC) adalah fungsi JavaScript yang menentukan apakah permintaan browser web (HTTP, HTTPS, dan FTP) langsung ke tujuan atau diteruskan ke server proxy web. Fungsi JavaScript yang terdapat dalam file PAC mendefinisikan fungsi tersebut:

- -
function FindProxyForURL(url, host) {
-  // ...
-}
- -

Sintaksis

- -
function FindProxyForURL(url, host)
- -

Parameter

- -
-
url
-
URL sedang diakses. Jalur dan komponen kueri https://URL dihilangkan. Di Chrome (versi 52 hingga 73), Anda dapat menonaktifkan ini dengan menyetel PacHttpsUrlStrippingEnabledke falsedalam kebijakan atau dengan meluncurkan dengan --unsafe-pac-urlbendera baris perintah (di Chrome 74, hanya bendera yang berfungsi, dan dari 75 dan seterusnya, tidak ada cara untuk menonaktifkan jalur- pengupasan; mulai Chrome 81, pengupasan jalur tidak berlaku untuk URL HTTP, tetapi ada minat untuk mengubah perilaku ini agar cocok dengan HTTPS); di Firefox, preferensinya adalah network.proxy.autoconfig_url.include_path.
-
host
-
Nama host diekstrak dari URL. Ini hanya untuk kenyamanan; itu adalah string yang sama seperti antara ://dan yang pertama :atau /setelah itu. Nomor port tidak termasuk dalam parameter ini. Ini dapat diekstrak dari URL bila perlu.
-
- -

Deskripsi

- -

Mengembalikan string yang menjelaskan konfigurasi. Format string ini ditentukan dalam format nilai pengembalian di bawah ini.

- -

Format nilai pengembalian

- - - -
-
DIRECT
-
Koneksi harus dibuat secara langsung, tanpa proxy apa pun
-
PROXY host:port
-
Proksi yang ditentukan harus digunakan
-
SOCKS host:port
-
Server SOCKS yang ditentukan harus digunakan
-
- -

Versi terbaru Firefox juga mendukung:

- -
-
HTTP host:port
-
Proksi yang ditentukan harus digunakan
-
HTTPS host:port
-
Proksi HTTPS yang ditentukan harus digunakan
-
SOCKS4 host:port
-
SOCKS5 host:port
-
Server SOCKS yang ditentukan (dengan versi SOCK yang ditentukan) harus digunakan
-
- -

Jika ada beberapa pengaturan yang dipisahkan titik koma, pengaturan paling kiri akan digunakan, sampai Firefox gagal membuat sambungan ke proxy. Dalam hal ini, nilai selanjutnya akan digunakan, dll.

- -

Browser akan secara otomatis mencoba proxy yang sebelumnya tidak merespons setelah 30 menit. Upaya tambahan akan berlanjut mulai dari satu jam, selalu menambahkan 30 menit ke waktu yang telah berlalu di antara upaya.

- -

Jika semua proxy sedang down, dan tidak ada opsi LANGSUNG yang ditentukan, browser akan menanyakan apakah proxy harus diabaikan untuk sementara, dan koneksi langsung diupayakan. Setelah 20 menit, browser akan menanyakan apakah proxy harus dicoba lagi, menanyakan lagi setelah 40 menit tambahan. Kueri akan berlanjut, selalu menambahkan 20 menit ke waktu yang telah berlalu di antara kueri.

- -

Contoh

- -
-
PROXY w3proxy.netscape.com:8080; PROXY mozilla.netscape.com:8081
-
Proksi utama adalah w3proxy: 8080; jika turun, mulailah menggunakan mozilla: 8081 hingga proxy utama muncul lagi.
-
PROXY w3proxy.netscape.com:8080; PROXY mozilla.netscape.com:8081; DIRECT
-
Sama seperti di atas, tetapi jika kedua proxy turun, secara otomatis mulai membuat koneksi langsung. (Pada contoh pertama di atas, Netscape akan menanyakan konfirmasi pengguna tentang membuat koneksi langsung; dalam hal ini, tidak ada intervensi pengguna.)
-
PROXY w3proxy.netscape.com:8080; SOCKS socks:1080
-
Gunakan SOCKS jika proxy utama mati.
-
- -

File konfigurasi otomatis harus disimpan ke file dengan ekstensi nama file .pac:

- -
proxy.pac
- -

Dan tipe MIME harus disetel ke:

- -
application/x-ns-proxy-autoconfig
- -

Selanjutnya, Anda harus mengkonfigurasi server Anda untuk memetakan ekstensi nama file .pac ke jenis MIME.

- -
-

Catatan:

- -
    -
  • Fungsi JavaScript harus selalu disimpan ke file dengan sendirinya tetapi tidak disematkan dalam file HTML atau file lainnya.
  • -
  • Contoh-contoh di akhir dokumen ini lengkap. Tidak ada sintaks tambahan yang diperlukan untuk menyimpannya ke dalam file dan menggunakannya. (Tentu saja, JavaScripts harus diedit untuk mencerminkan nama domain dan / atau subnet situs Anda.)
  • -
-
- -

Fungsi dan lingkungan yang telah ditentukan sebelumnya

- -

Fungsi-fungsi ini dapat digunakan untuk membuat file PAC:

- - - -
-

Catatan: pactester (bagian dari paket pacparser ) digunakan untuk menguji contoh sintaks berikut.

- -
    -
  • File PAC diberi nama proxy.pac
  • -
  • Baris perintah: pactester -p ~/pacparser-master/tests/proxy.pac -u http://www.mozilla.org(melewati hostparameter www.mozilla.orgdan urlparameter http://www.mozilla.org)
  • -
-
- -

isPlainHostName ()

- -

Sintaksis

- -
isPlainHostName(host)
- -

Parameter

- -
-
tuan rumah
-
Nama host dari URL (tidak termasuk nomor port).
-
- -

Deskripsi

- -

Benar jika dan hanya jika tidak ada nama domain di nama host (tidak ada titik).

- -

Contoh

- -
isPlainHostName("www.mozilla.org") // false
-isPlainHostName("www") // true
-
- -

dnsDomainIs()

- -

Sintaksis

- -
dnsDomainIs(host, domain)
- -

Parameter

- -
-
tuan rumah
-
Apakah nama host dari URL.
-
domain
-
Apakah nama domain untuk menguji nama host.
-
- -

Deskripsi

- -

Mengembalikan nilai benar jika dan hanya jika domain nama host cocok.

- -

Contoh

- -
dnsDomainIs("www.mozilla.org", ".mozilla.org") // true
-dnsDomainIs("www", ".mozilla.org") // false
-
- -

localHostOrDomainIs ()

- -

Sintaksis

- -
localHostOrDomainIs(host, hostdom)
- -

Parameter

- -
-
tuan rumah
-
Nama host dari URL.
-
tuan rumah
-
Nama host yang sepenuhnya memenuhi syarat untuk dicocokkan.
-
- -

Deskripsi

- -

Benar jika nama host sama persis dengan nama host yang ditentukan, atau jika tidak ada bagian nama domain dalam nama host, tetapi nama host yang tidak memenuhi syarat cocok.

- -

Contoh

- -
localHostOrDomainIs("www.mozilla.org" , "www.mozilla.org") // true (exact match)
-localHostOrDomainIs("www"             , "www.mozilla.org") // true (hostname match, domain not specified)
-localHostOrDomainIs("www.google.com"  , "www.mozilla.org") // false (domain name mismatch)
-localHostOrDomainIs("home.mozilla.org", "www.mozilla.org") // false (hostname mismatch)
- -

isResolvable ()

- -

Sintaksis

- -
isResolvable(host)
- -

Parameter

- -
-
tuan rumah
-
adalah nama host dari URL.
-
- -

Mencoba menyelesaikan nama host. Mengembalikan nilai benar jika berhasil.

- -

Contoh:

- -
isResolvable("www.mozilla.org") // true
-
- -

isInNet ()

- -

Sintaksis

- -
isInNet(host, pattern, mask)
- -

Parameter

- -
-
tuan rumah
-
nama host DNS, atau alamat IP. Jika nama host dilewatkan, itu akan diselesaikan menjadi alamat IP dengan fungsi ini.
-
pola
-
pola alamat IP dalam format yang dipisahkan titik.
-
topeng
-
mask untuk pola alamat IP yang menginformasikan bagian mana dari alamat IP yang harus dicocokkan. 0 berarti abaikan, 255 berarti cocok.
-
- -

True jika dan hanya jika alamat IP dari host cocok dengan pola alamat IP yang ditentukan.

- -

Spesifikasi pola dan topeng dilakukan dengan cara yang sama seperti untuk konfigurasi SOCKS.

- -

Contoh:

- -
function alert_eval(str) { alert(str + ' is ' + eval(str)) }
-function FindProxyForURL(url, host) {
-  alert_eval('isInNet(host, "63.245.213.24", "255.255.255.255")')
-  // "PAC-alert: isInNet(host, "63.245.213.24", "255.255.255.255") is true"
-}
-
- -

dnsResolve ()

- -
dnsResolve(host)
- -

Parameter

- -
-
tuan rumah
-
nama host untuk diselesaikan.
-
- -

Menyelesaikan nama host DNS yang diberikan menjadi alamat IP, dan mengembalikannya dalam format yang dipisahkan titik sebagai string.

- -

Contoh

- -
dnsResolve("www.mozilla.org"); // returns the string "104.16.41.2"
- -

convert_addr ()

- -

Sintaksis

- -
convert_addr(ipaddr)
- -

Parameter

- -
-
ipaddr
-
Alamat bertitik apa pun seperti alamat IP atau topeng.
-
- -

Menggabungkan empat byte yang dipisahkan titik menjadi satu kata 4-byte dan mengubahnya menjadi desimal.

- -

Contoh

- -
convert_addr("104.16.41.2"); // returns the decimal number 1745889538
- -

myIpAddress ()

- -

Sintaksis

- -
myIpAddress()
- -

Parameter

- -

(tidak ada)

- -

Mengembalikan alamat IP server dari mesin tempat Firefox dijalankan, sebagai string dalam format bilangan bulat yang dipisahkan titik.

- -
-

myIpAddress () mengembalikan alamat IP yang sama dengan alamat server yang dikembalikan oleh nslookup localhost mesin Linux. Itu tidak mengembalikan alamat IP publik.

-
- -

Contoh

- -
myIpAddress() //returns the string "127.0.1.1" if you were running Firefox on that localhost
- -

dnsDomainLevels ()

- -

Sintaksis

- -
dnsDomainLevels(host)
- -

Parameter

- -
-
tuan rumah
-
adalah nama host dari URL.
-
- -

Mengembalikan angka (bilangan bulat) dari level domain DNS (jumlah titik) di nama host.

- -

Contoh:

- -
dnsDomainLevels("www");             // 0
-dnsDomainLevels("mozilla.org");     // 1
-dnsDomainLevels("www.mozilla.org"); // 2
-
- -

shExpMatch ()

- -

Sintaksis

- -
shExpMatch(str, shexp)
- -

Parameter

- -
-
str
-
adalah sembarang string untuk dibandingkan (mis. URL, atau nama host).
-
shexp
-
adalah ekspresi shell untuk dibandingkan.
-
- -

Mengembalikan nilai benar jika string cocok dengan ekspresi shell yang ditentukan.

- -

Perhatikan bahwa polanya adalah ekspresi shell glob , bukan ekspresi reguler. *dan ?selalu didukung, sementara [characters]dan [^characters]didukung oleh beberapa implementasi termasuk Firefox. Ini terutama karena ekspresi diterjemahkan ke RegExp melalui subsitusi [.*?]. Untuk cara yang dapat diandalkan untuk menggunakan sintaks RegExp ini, cukup gunakan RegExp sebagai gantinya.

- -

Contoh

- -
shExpMatch("http://home.netscape.com/people/ari/index.html"     , "*/ari/*"); // returns true
-shExpMatch("http://home.netscape.com/people/montulli/index.html", "*/ari/*"); // returns false
- -

weekdayRange ()

- -

Sintaksis

- -
weekdayRange(wd1, wd2, [gmt])
- -
-

Catatan: (Sebelum Firefox 49) wd1 harus lebih kecil dari wd2 jika Anda ingin fungsi mengevaluasi parameter ini sebagai rentang. Lihat peringatan di bawah.

-
- -

Parameter

- -
-
wd1 dan wd2
-
Salah satu string hari kerja yang dipesan:
-
-
"SUN"|"MON"|"TUE"|"WED"|"THU"|"FRI"|"SAT"
-
-
waktu Greenwich
-
Apakah string "GMT" atau ditinggalkan.
-
- -

Hanya parameter pertama yang wajib diisi. Entah yang kedua, ketiga, atau keduanya mungkin ditinggalkan.

- -

Jika hanya satu parameter yang ada, fungsi mengembalikan nilai true pada hari kerja yang diwakili oleh parameter. Jika string "GMT" ditetapkan sebagai parameter kedua, waktu dianggap dalam GMT. Jika tidak, mereka diasumsikan berada dalam zona waktu lokal.

- -

Jika wd1 dan wd1 ditentukan, kondisinya benar jika hari kerja saat ini berada di antara dua hari kerja yang dipesan . Batas bersifat inklusif, tetapi batasnya teratur . Jika parameter "GMT" ditentukan, waktu dianggap dalam GMT. Jika tidak, zona waktu lokal digunakan.

- -
-

Urutan hari penting ; Sebelum Firefox 49, akan selalu bernilai true. Sekarang hanya akan mengevaluasi benar jika hari ini adalah Rabu atau Minggu.weekdayRange("SUN", "SAT")weekdayRange("WED", "SUN")

-
- -

Contoh

- -
weekdayRange("MON", "FRI");        // returns true Monday through Friday (local timezone)
-weekdayRange("MON", "FRI", "GMT"); // returns true Monday through Friday (GMT timezone)
-weekdayRange("SAT");               // returns true on Saturdays local time
-weekdayRange("SAT", "GMT");        // returns true on Saturdays GMT time
-weekdayRange("FRI", "MON");        // returns true Friday and Monday only (note, order does matter!)
- -

dateRange()

- -

Syntax

- -
dateRange(<day> | <month> | <year>, [gmt])  // ambiguity is resolved by assuming year is greater than 31
-dateRange(<day1>, <day2>, [gmt])
-dateRange(<month1>, <month2>, [gmt])
-dateRange(<year1>, <year2>, [gmt])
-dateRange(<day1>, <month1>, <day2>, <month2>, [gmt])
-dateRange(<month1>, <year1>, <month2>, <year2>, [gmt])
-dateRange(<day1>, <month1>, <year1>, <day2>, <month2>, <year2>, [gmt])
- -
-

Note: (Before Firefox 49) day1 must be less than day2, month1 must be less than month2, and year1 must be less than year2 if you want the function to evaluate these parameters as a range. See the warning below.

-
- -

Parameters

- -
-
day
-
Is the ordered day of the month between 1 and 31 (as an integer).
-
- -
1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31
- -
-
month
-
Is one of the ordered month strings below.
-
- -
"JAN"|"FEB"|"MAR"|"APR"|"MAY"|"JUN"|"JUL"|"AUG"|"SEP"|"OCT"|"NOV"|"DEC"
- -
-
year
-
Is the ordered full year integer number. For example, 2016 (not 16).
-
gmt
-
Is either the string "GMT", which makes time comparison occur in GMT timezone, or is left out. If left unspecified, times are taken to be in the local timezone.
-
- -

Jika hanya satu nilai yang ditentukan (dari setiap kategori: hari, bulan, tahun), fungsi mengembalikan nilai sebenarnya hanya pada hari yang cocok dengan spesifikasi tersebut. Jika kedua nilai ditentukan, hasilnya adalah benar di antara waktu-waktu tersebut, termasuk batas, tetapi batasnya diurutkan .

- -
-

Urutan hari, bulan, dan tahun penting ; Sebelum Firefox 49, akan selalu mengevaluasi ke . Sekarang hanya akan mengevaluasi benar jika bulan ini adalah Desember atau Januari.dateRange("JAN", "DEC")truedateRange("DEC", "JAN")

-
- -

Contoh

- -
dateRange(1);            // returns true on the first day of each month, local timezone
-dateRange(1, "GMT")      // returns true on the first day of each month, GMT timezone
-dateRange(1, 15);        // returns true on the first half of each month
-dateRange(24, "DEC");    // returns true on 24th of December each year
-dateRange("JAN", "MAR"); // returns true on the first quarter of the year
-
-dateRange(1, "JUN", 15, "AUG");
-// returns true from June 1st until August 15th, each year
-// (including June 1st and August 15th)
-
-dateRange(1, "JUN", 1995, 15, "AUG", 1995);
-// returns true from June 1st, 1995, until August 15th, same year
-
-dateRange("OCT", 1995, "MAR", 1996);
-// returns true from October 1995 until March 1996
-// (including the entire month of October 1995 and March 1996)
-
-dateRange(1995);
-// returns true during the entire year of 1995
-
-dateRange(1995, 1997);
-// returns true from beginning of year 1995 until the end of year 1997
- -

rentang waktu()

- -

Sintaksis

- -
// The full range of expansions is analogous to dateRange.
-timeRange(<hour1>, <min1>, <sec1>, <hour2>, <min2>, <sec2>, [gmt])
- -
-

Catatan: (Sebelum Firefox 49) kategori hour1, min1, sec1 harus kurang dari kategori hour2, min2, sec2 jika Anda ingin fungsi mengevaluasi parameter ini sebagai rentang. Lihat peringatan di bawah.

-
- -

Parameter

- -
-
jam
-
Adalah jam dari 0 hingga 23. (0 adalah tengah malam, 23 adalah 11 malam.)
-
min
-
Menit dari 0 hingga 59.
-
detik
-
Detik dari 0 hingga 59.
-
waktu Greenwich
-
Baik string "GMT" untuk zona waktu GMT, atau tidak ditentukan, untuk zona waktu lokal.
-
- -

Jika hanya satu nilai yang ditentukan (dari setiap kategori: jam, menit, detik), fungsi mengembalikan nilai sebenarnya hanya pada waktu yang sesuai dengan spesifikasi tersebut. Jika kedua nilai ditentukan, hasilnya adalah benar di antara waktu-waktu tersebut, termasuk batas, tetapi batasnya diurutkan .

- -
-

Urutan jam, menit, materi kedua ; Sebelum Firefox 49, akan selalu bernilai true. Sekarang hanya akan mengevaluasi benar jika jam saat ini adalah 23:00 atau tengah malam.timeRange(0, 23)timeRange(23, 0)

-
- -

Contoh

- -
timerange(12);                // returns true from noon to 1pm
-timerange(12, 13);            // returns true from noon to 1pm
-timerange(12, "GMT");         // returns true from noon to 1pm, in GMT timezone
-timerange(9, 17);             // returns true from 9am to 5pm
-timerange(8, 30, 17, 00);     // returns true from 8:30am to 5:00pm
-timerange(0, 0, 0, 0, 0, 30); // returns true between midnight and 30 seconds past midnight
- -

Contoh 1

- -

Gunakan proxy untuk semuanya kecuali host lokal

- -
-

Catatan: Karena semua contoh berikut sangat spesifik, mereka belum diuji.

-
- -

All hosts which aren't fully qualified, or the ones that are in local domain, will be connected to directly. Everything else will go through w3proxy.mozilla.org:8080. If the proxy goes down, connections become direct automatically:

- -
function FindProxyForURL(url, host) {
-  if (isPlainHostName(host) || dnsDomainIs(host, ".mozilla.org")) {
-    return "DIRECT";
-  } else {
-    return "PROXY w3proxy.mozilla.org:8080; DIRECT";
-  }
-}
- -
-

Note: This is the simplest and most efficient autoconfig file for cases where there's only one proxy.

-
- -

Example 2

- -

As above, but use proxy for local servers which are outside the firewall

- -

If there are hosts (such as the main Web server) that belong to the local domain but are outside the firewall and are only reachable through the proxy server, those exceptions can be handled using the localHostOrDomainIs() function:

- -
function FindProxyForURL(url, host) {
-  if (
-    (isPlainHostName(host) || dnsDomainIs(host, ".mozilla.org")) &&
-    !localHostOrDomainIs(host, "www.mozilla.org") &&
-    !localHostOrDoaminIs(host, "merchant.mozilla.org")
-  ) {
-    return "DIRECT";
-  } else {
-    return "PROXY w3proxy.mozilla.org:8080; DIRECT";
-  }
-}
- -

The above example will use the proxy for everything except local hosts in the mozilla.org domain, with the further exception that hosts www.mozilla.org and merchant.mozilla.org will go through the proxy.

- -
-

Note the order of the above exceptions for efficiency: localHostOrDomainIs() functions only get executed for URLs that are in local domain, not for every URL. Be careful to note the parentheses around the or expression before the and expression to achieve the above-mentioned efficient behaviour.

-
- -

Example 3

- -

Use proxy only if cannot resolve host

- -

This example will work in an environment where the internal DNS server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable:

- -
function FindProxyForURL(url, host) {
-  if (isResolvable(host))
-    return "DIRECT";
-  else
-    return "PROXY proxy.mydomain.com:8080";
-}
- -

The above requires consulting the DNS every time; it can be grouped intelligently with other rules so that DNS is consulted only if other rules do not yield a result:

- -
function FindProxyForURL(url, host) {
-  if (
-    isPlainHostName(host) ||
-    dnsDomainIs(host, ".mydomain.com") ||
-    isResolvable(host)
-  ) {
-    return "DIRECT";
-  } else {
-    return "PROXY proxy.mydomain.com:8080";
-  }
-}
- -

Example 4

- -

Subnet based decisions

- -

In this example all of the hosts in a given subnet are connected-to directly, others are connected through the proxy:

- -
function FindProxyForURL(url, host) {
-  if (isInNet(host, "198.95.0.0", "255.255.0.0"))
-    return "DIRECT";
-  else
-    return "PROXY proxy.mydomain.com:8080";
-}
- -

Again, use of the DNS server in the above can be minimized by adding redundant rules in the beginning:

- -
function FindProxyForURL(url, host) {
-  if (
-    isPlainHostName(host) ||
-    dnsDomainIs(host, ".mydomain.com") ||
-    isInNet(host, "198.95.0.0", "255.255.0.0")
-  ) {
-    return "DIRECT";
-  } else {
-    return "PROXY proxy.mydomain.com:8080";
-  }
-}
- -

Example 5

- -

Load balancing/routing based on URL patterns

- -

This example is more sophisticated. There are four (4) proxy servers; one of them is a hot stand-by for all of the other ones, so if any of the remaining three goes down the fourth one will take over. Furthermore, the three remaining proxy servers share the load based on URL patterns, which makes their caching more effective (there is only one copy of any document on the three servers - as opposed to one copy on each of them). The load is distributed like this:

- - - - - - - - - - - - - - - - - - - - - - - - -
ProxyPurpose
#1.com domain
#2.edu domain
#3all other domains
#4hot stand-by
- -

All local accesses are desired to be direct. All proxy servers run on the port 8080 (they don't need to, you can just change your port but remember to modify your configuations on both side). Note how strings can be concatenated with the + operator in JavaScript.

- -
function FindProxyForURL(url, host) {
-
-  if (isPlainHostName(host) || dnsDomainIs(host, ".mydomain.com"))
-    return "DIRECT";
-
-  else if (shExpMatch(host, "*.com"))
-    return "PROXY proxy1.mydomain.com:8080; " +
-           "PROXY proxy4.mydomain.com:8080";
-
-  else if (shExpMatch(host, "*.edu"))
-    return "PROXY proxy2.mydomain.com:8080; " +
-           "PROXY proxy4.mydomain.com:8080";
-
-  else
-    return "PROXY proxy3.mydomain.com:8080; " +
-           "PROXY proxy4.mydomain.com:8080";
-}
- -

Example 6

- -

Setting a proxy for a specific protocol

- -

Most of the standard JavaScript functionality is available for use in the FindProxyForURL() function. As an example, to set different proxies based on the protocol the {{jsxref("String.prototype.startsWith()", "startsWith()")}} function can be used:

- -
function FindProxyForURL(url, host) {
-
-  if (url.startsWith("http:"))
-    return "PROXY http-proxy.mydomain.com:8080";
-
-  else if (url.startsWith("ftp:"))
-    return "PROXY ftp-proxy.mydomain.com:8080";
-
-  else if (url.startsWith(“gopher:"))
-    return "PROXY gopher-proxy.mydomain.com:8080";
-
-  else if (url.startsWith("https:") || url.startsWith("snews:"))
-    return "PROXY security-proxy.mydomain.com:8080";
-
-  else
-    return "DIRECT";
-
-}
- -
-

Note: The same can be accomplished using the shExpMatch() function described earlier.

-
- -

For example:

- -
// ...
-if (shExpMatch(url, "http:*")) {
-  return "PROXY http-proxy.mydomain.com:8080";
-}
-// ...
- -
-

The autoconfig file can be output by a CGI script. This is useful, for example, when making the autoconfig file act differently based on the client IP address (the REMOTE_ADDR environment variable in CGI).

- -

Usage of isInNet(), isResolvable() and dnsResolve() functions should be carefully considered, as they require the DNS server to be consulted. All the other autoconfig-related functions are mere string-matching functions that don't require the use of a DNS server. If a proxy is used, the proxy will perform its DNS lookup which would double the impact on the DNS server. Most of the time these functions are not necessary to achieve the desired result.

-
- -

History and implementation

- -

Proxy auto-config was introduced into Netscape Navigator 2.0 in the late 1990s, at the same time when JavaScript was introduced. Open-sourcing Netscape eventually lead to Firefox itself.

- -

Oleh karena itu, implementasi PAC yang paling "asli" dan pustaka JavaScript-nya nsProxyAutoConfig.jsditemukan di versi awal Firefox. Utilitas ini ditemukan di banyak sistem sumber terbuka lainnya termasuk Chromium . Firefox kemudian mengintegrasikan file tersebut menjadi ProxyAutoConfig.cppliteral string C ++. Untuk mengekstraknya ke dalam filenya sendiri, cukup dengan menyalin potongan ke JavaScript dengan console.logperintah untuk mencetaknya.

- -

Microsoft secara umum membuat implementasinya sendiri. Dulu ada beberapa masalah dengan pustaka mereka , tetapi sebagian besar telah diselesaikan sekarang. Mereka telah mendefinisikan beberapa fungsi sufiks "Ex" baru di sekitar bagian penanganan alamat untuk mendukung IPv6. Fitur ini didukung oleh Chromium, tetapi belum didukung oleh Firefox ( bugzilla # 558253 ).

diff --git a/files/id/web/http/status/100/index.html b/files/id/web/http/status/100/index.html deleted file mode 100644 index 3f2f0db1d2..0000000000 --- a/files/id/web/http/status/100/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: 100 Continue -slug: Web/HTTP/Status/100 -tags: - - HTTP - - Informasi - - Status code -translation_of: Web/HTTP/Status/100 ---- -
{{HTTPSidebar}}
- -

HTTP 100 Continue menginformasikan status kode respon yang menandakan bahwa semuanya OK dan klien dapat melanjutkan dengan permintaan atau mengabaikan jika telah terselesaikan.

- -

Untuk bisa mendapatkan server check pada header permintaan, klien harus mengirim Expect: 100-continue sebagai header pada permintaan inisial dan mendapatan kode status respon 100 Continue sebelum mengirim konten atau body.

- -

Status

- -
100 Continue
- -

Spesifikasi

- - - - - - - - - - - - -
SpesifikasiTitle
{{RFC("7231", "100 Continue" , "6.2.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
- -

Kompabilitas Browser

- - - -

{{Compat("http/status", "100")}}

- -

Lihat Juga

- - diff --git a/files/id/web/http/status/200/index.html b/files/id/web/http/status/200/index.html deleted file mode 100644 index 76c06a3e1e..0000000000 --- a/files/id/web/http/status/200/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: 200 OK -slug: Web/HTTP/Status/200 -translation_of: Web/HTTP/Status/200 ---- -
{{HTTPSidebar}}
- -

HTTP 200 OK respon status sukses merupakan kode respon yang menandakan bahwa request sukses. respon 200 dapat dichace secara default.

- -

Arti dari sukses tergantung pada fungsi request HTTP:

- - - -

Kesuksesan hasil dari {{HTTPMethod("PUT")}} atau {{HTTPMethod("DELETE")}} biasanya bukan 200 OK tapi {{HTTPStatus("204")}} No Content (atau {{HTTPStatus("201")}} Created ketika resource diunggah pertama kali).

- -

Status

- -
200 OK
- -

Spesifikasi

- - - - - - - - - - - - -
SpesifikasiJudul
{{RFC("7231", "200 OK" , "6.3.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
- -

Kompabilitas Browser

- - - -

{{Compat("http.status.200")}}

- -

Lihat Juga

- - diff --git a/files/id/web/http/status/400/index.html b/files/id/web/http/status/400/index.html deleted file mode 100644 index 3d98750338..0000000000 --- a/files/id/web/http/status/400/index.html +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: 400 Bad Request -slug: Web/HTTP/Status/400 -tags: - - Galat Klien - - HTTP - - Kode status - - Referensi - - Status kode HTTP -translation_of: Web/HTTP/Status/400 ---- -
{{HTTPSidebar}}
- -

Kode Respon HTTP 400 Bad Request mengindikasikan bahwa server tidak bisa atau tidak akan memproses permintaan karena sesuatu yang dianggap sebagai kesalahan klien (seperti sintaks permintaan yang jelek, pesan request yang tidak valid, atau permintaan yang menipu.

- -
-

Klien seharusnya tidak mengulangi permintaan yang sama tanpa perubahan.

-
- -

Status

- -
400 Bad Request 
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpecificationTitle
{{RFC("7231", "400 Bad Request" , "6.5.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
diff --git a/files/id/web/http/status/403/index.html b/files/id/web/http/status/403/index.html deleted file mode 100644 index 71dc858a2f..0000000000 --- a/files/id/web/http/status/403/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: 403 Forbidden -slug: Web/HTTP/Status/403 -tags: - - Galat Klien - - HTTP - - Kode status - - Referensi -translation_of: Web/HTTP/Status/403 ---- -
{{HTTPSidebar}}
- -

Kode respon HTTP 403 Forbidden mengindikasikan bahwa server memahami permintaan tetapi menolak untuk mengesahkannya.

- -

Kode status ini mirip dengan {{HTTPStatus("401")}}, tetapi dalam kasus ini, autentikasi ulang tidak akan memberi perubahan. Aksesnya dilarang secara permanen dan diikat pada logika aplikasi, seperti kurangnya hak akses untuk mendapatkan sumber daya.

- -

Status

- -
403 Forbidden
- -

Contoh respon

- -
HTTP/1.1 403 Forbidden
-Date: Wed, 21 Oct 2015 07:28:00 GMT
-
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpecificationTitle
{{RFC("7231", "403 Forbidden" , "6.5.3")}}HTTP/1.1: Semantics and Content
- -

Dukungan peramban

- - - -

{{Compat("http.status.403")}}

- -

Lihat juga

- - diff --git a/files/id/web/http/status/404/index.html b/files/id/web/http/status/404/index.html deleted file mode 100644 index 10c1e4e0a5..0000000000 --- a/files/id/web/http/status/404/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: 404 Not Found -slug: Web/HTTP/Status/404 -tags: - - Galat Klien - - HTTP - - Kode status - - Peramban -translation_of: Web/HTTP/Status/404 ---- -
{{HTTPSidebar}}
- -

Kode respon HTTP 404 Not Found mengindikasikan bahwa server tidak dapat menemukan sumber daya yang diminta. Link yang menuju halaman 404 biasanya disebut dengan broken atau dead links, dan bisa menjadi subjek kepada link rot.

- -

Status kode 404 tidak mengindikasikan bahwa sumber daya tidak ditemukan sementara atau secara permanen. Apabila sumber daya dihapus secara permanen, {{HTTPStatus("410")}} (Gone) harus digunakan dibandingkan status 404.

- -

Status

- -
404 Not Found
- -

Halaman galat khusus

- -

Banyak web sites menyesuaikan tampilan dari halaman 404 supaya lebih membantu pengguna dan memberikan petunjuk apa yang harus dilakukan seterusnya. Server Apache dapat dikonfigurasi dengan file .htaccess dengan potongan kode berikut.

- -
ErrorDocument 404 /notfound.html
- -

Untuk contoh dari halaman 404 khusus, lihat Halaman 404 MDN.

- -
-

Desain khusus merupakan hal yang baik. Buat halaman 404 Anda menjadi lucu dan manusiawi, tetapi jangan membuat bingung pengguna.

-
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpecificationTitle
{{RFC("7231", "404 Not Found" , "6.5.4")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
- -

Dukungan Peramban

- - - -

{{Compat("http.status.404")}}

- -

Lihat Juga

- - diff --git a/files/id/web/http/status/405/index.html b/files/id/web/http/status/405/index.html deleted file mode 100644 index 651db0f858..0000000000 --- a/files/id/web/http/status/405/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: 405 Metode tidak Diizinkan -slug: Web/HTTP/Status/405 -tags: - - Galat Klien - - HTTP - - Referensi - - Status kode - - Status kode HTTP -translation_of: Web/HTTP/Status/405 ---- -
{{HTTPSidebar}}
- -

Kode respon HTTP 405 Method Not Allowed mengindikasikan bahwa metode permintaan dikenali oleh server tetapi tidak didukung oleh target sumber daya. Server harus menyematkan Allow header field di dalam respon 405 berisi daftar dari metode permintaan yang didukung oleh target sumber daya.

- -

Status

- -
405 Method Not Allowed
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpecificationTitle
{{RFC("7231", "405 Method Not Allowed" , "6.5.5")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
- -

Lihat juga

- - diff --git a/files/id/web/http/status/410/index.html b/files/id/web/http/status/410/index.html deleted file mode 100644 index 42ac089598..0000000000 --- a/files/id/web/http/status/410/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: 410 Gone -slug: Web/HTTP/Status/410 -tags: - - Galat Klien - - HTTP - - Kode status - - Referensi -translation_of: Web/HTTP/Status/410 ---- -
{{HTTPSidebar}}
- -

Kode respon HTTP 410 Gone mengindikasikan bahwa akses ke sumber daya tidak lagi tersedia di server asal dengan kondisi akan tidak tersedia secara permanen.

- -

Apabila Anda tidak tahu apakah kondisi ini hanya sementara atau permanen, kode error {{HTTPStatus(404)}} sebaiknya digunakan.

- -
-

Catatan: Sebuah respon 410 dapat disimpan di dalam cache secara bawaan.

-
- -

Status

- -
410 Gone
- -

Spesifikasi

- - - - - - - - - - - - - - -
SpecificationTitle
{{RFC("7231", "410 Gone" , "6.5.9")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
- -

Dukungan Peramban

- -

The information shown below has been pulled from MDN's GitHub (https://github.com/mdn/browser-compat-data).

- - - -

{{Compat("http.status.410")}}

- -

Lihat Juga

- - diff --git a/files/id/web/http/status/500/index.html b/files/id/web/http/status/500/index.html deleted file mode 100644 index ce5c5157fb..0000000000 --- a/files/id/web/http/status/500/index.html +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: 500 Internal Server Error -slug: Web/HTTP/Status/500 -translation_of: Web/HTTP/Status/500 ---- -
{{HTTPSidebar}}
- -

HTTP kode respons kesalahan server menunjukkan bahwa server mengalami kondisi tak terduga yang menghalanginya memenuhi permintaan.

- -

Respons kesalahan ini adalah turunan "mencakup-semua" respons. Seringkali respons server pengelola catatan seperti kode status 500 dengan lebih banyak detail tentang permintaan untuk mencegah kesalahan terjadi lagi di masa mendatang.

- -

Status

- -
500 Kesalahan Server dari Dalam
-
- -

Specifications

- - - - - - - - - - - - -
SpecificationTitle
{{RFC("7231", "" , "6.6.1")}}Protokol Transfer Hiperteks (HTTP / 1.1): Semantik dan Konten
- -

Kompatibilias browser

- - - - - -

{{Compat("http.status.500")}}

diff --git a/files/id/web/http/status/index.html b/files/id/web/http/status/index.html deleted file mode 100644 index 066d40771e..0000000000 --- a/files/id/web/http/status/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: HTTP response status codes -slug: Web/HTTP/Status -translation_of: Web/HTTP/Status ---- -
{{HTTPSidebar}}
- -

kode status respon HTTP menunjukkan apakah permintaan HTTP tertentu telah berhasil diselesaikan. Tanggapan dikelompokkan dalam lima kelas: tanggapan informasi, tanggapan yang sukses, pengalihan, kesalahan klien, dan server kesalahan.

- -

Respon informasi

- -
-
{{HTTPStatus(100, "100 Continue")}}
-
Tanggapan sementara ini menunjukkan bahwa segala sesuatu sejauh ini adalah OK dan bahwa klien harus melanjutkan dengan permintaan atau mengabaikannya jika sudah selesai.
-
{{HTTPStatus(101, "101 Switching Protocol")}}
-
Kode ini dikirim sebagai tanggapan ke header permintaan {{HTTPHeader ("Upgrade")}} oleh klien, dan menunjukkan protokol yang digunakan oleh server.
-
{{HTTPStatus(102, "102 Processing")}} ({{Glossary("WebDAV")}})
-
Kode ini menunjukkan bahwa server telah menerima dan memproses permintaan, tetapi belum ada respons.
-
- -

Response Sukses

- -
-
{{HTTPStatus(200, "200 OK")}}
-
Permintaan telah berhasil . Arti keberhasilan bervariasi tergantung pada metode HTTP :
- GET: The resource has been fetched and is transmitted in the message body.
- HEAD: The entity headers are in the message body.
- POST: The resource describing the result of the action is transmitted in the message body.
- TRACE: The message body contains the request message as received by the server
-
{{HTTPStatus(201, "201 Created")}}
-
The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request.
-
{{HTTPStatus(202, "202 Accepted")}}
-
The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.
-
{{HTTPStatus(203, "203 Non-Authoritative Information")}}
-
This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.
-
{{HTTPStatus(204, "204 No Content")}}
-
There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.
-
{{HTTPStatus(205, "205 Reset Content")}}
-
This response code is sent after accomplishing request to tell user agent reset document view which sent this request.
-
{{HTTPStatus(206, "206 Partial Content")}}
-
This response code is used because of range header sent by the client to separate download into multiple streams.
-
- -

Redirection messages

- -
-
{{HTTPStatus(300, "300 Multiple Choice")}}
-
The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses.
-
{{HTTPStatus(301, "301 Moved Permanently")}}
-
This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response.
-
{{HTTPStatus(302, "302 Found")}}
-
This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
-
{{HTTPStatus(303, "303 See Other")}}
-
Server sent this response to directing client to get requested resource to another URI with an GET request.
-
{{HTTPStatus(304, "304 Not Modified")}}
-
This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.
-
{{HTTPStatus(305, "305 Use Proxy")}}
-
This means requested response must be accessed by a proxy. This response code is not largely supported because security reasons.
-
{{HTTPStatus(306, "306 unused")}}
-
This response code is no longer used, it is just reserved currently. It was used in a previous version of the HTTP 1.1 specification.
-
{{HTTPStatus(307, "307 Temporary Redirect")}}
-
Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
-
{{HTTPStatus(308, "308 Permanent Redirect")}}
-
This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
-
- -

Client error responses

- -
-
{{HTTPStatus(400, "400 Bad Request")}}
-
Respons ini berarti server tidak dapat memahami permintaan karena sintaks yang tidak valid.
-
{{HTTPStatus(401, "401 Unauthorized")}}
-
Authentication is needed to get requested response. This is similar to 403, but in this case, authentication is possible.
-
{{HTTPStatus(402, "402 Payment Required")}}
-
This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.
-
{{HTTPStatus(403, "403 Forbidden")}}
-
Client does not have access rights to the content so server is rejecting to give proper response.
-
{{HTTPStatus(404, "404 Not Found")}}
-
Server can not find requested resource. This response code probably is most famous one due to its frequency to occur in web.
-
{{HTTPStatus(405, "405 Method Not Allowed")}}
-
The request method is known by the server but has been disabled and cannot be used. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.
-
{{HTTPStatus(406, "406 Not Acceptable")}}
-
This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent.
-
{{HTTPStatus(407, "407 Proxy Authentication Required")}}
-
This is similar to 401 but authentication is needed to be done by a proxy.
-
{{HTTPStatus(408, "408 Request Timeout")}}
-
This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome or IE9, use HTTP preconnection mechanisms to speed up surfing (see {{ bug(634278) }}, which tracks the future implementation of such a mechanism in Firefox). Also note that some servers merely shut down the connection without sending this message.
-
{{HTTPStatus(409, "409 Conflict")}}
-
This response would be sent when a request conflict with current state of server.
-
{{HTTPStatus(410, "410 Gone")}}
-
This response would be sent when requested content has been deleted from server.
-
{{HTTPStatus(411, "411 Length Required")}}
-
Server rejected the request because the Content-Length header field is not defined and the server requires it.
-
{{HTTPStatus(412, "412 Precondition Failed")}}
-
The client has indicated preconditions in its headers which the server does not meet.
-
{{HTTPStatus(413, "413 Payload Too Large")}}
-
Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.
-
{{HTTPStatus(414, "414 URI Too Long")}}
-
The URI requested by the client is longer than the server is willing to interpret.
-
{{HTTPStatus(415, "415 Unsupported Media Type")}}
-
The media format of the requested data is not supported by the server, so the server is rejecting the request.
-
{{HTTPStatus(416, "416 Requested Range Not Satisfiable")}}
-
The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.
-
{{HTTPStatus(417, "417 Expectation Failed")}}
-
This response code means the expectation indicated by the Expect request header field can't be met by the server.
-
{{HTTPStatus(421, "421 Misdirected Request")}}
-
The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
-
{{HTTPStatus(426, "426 Upgrade Required")}}
-
The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server MUST send an Upgrade header field in a 426 response to indicate the required protocol(s) (Section 6.7 of [RFC7230]).
-
{{HTTPStatus(428, "428 Precondition Required")}}
-
The origin server requires the request to be conditional. Intended to prevent "the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
-
{{HTTPStatus(429, "429 Too Many Requests")}}
-
The user has sent too many requests in a given amount of time ("rate limiting").
-
{{HTTPStatus(431, "431 Request Header Fields Too Large")}}
-
The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.
-
{{HTTPStatus(451, "451 Unavailable For Legal Reasons")}}
-
The user requests an illegal resource, such as a web page censored by a government.
-
- -

Server error responses

- -
-
{{HTTPStatus(500, "500 Internal Server Error")}}
-
The server has encountered a situation it doesn't know how to handle.
-
{{HTTPStatus(501, "501 Not Implemented")}}
-
The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.
-
{{HTTPStatus(502, "502 Bad Gateway")}}
-
This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
-
{{HTTPStatus(503, "503 Service Unavailable")}}
-
The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
-
{{HTTPStatus(504, "504 Gateway Timeout")}}
-
This error response is given when the server is acting as a gateway and cannot get a response in time.
-
{{HTTPStatus(505, "505 HTTP Version Not Supported")}}
-
The HTTP version used in the request is not supported by the server.
-
{{HTTPStatus(506, "506 Variant Also Negotiates")}}
-
The server has an internal configuration error: transparent content negotiation for the request results in a circular reference.
-
{{HTTPStatus(507, "507 Variant Also Negotiates")}}
-
The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
-
{{HTTPStatus(511, "511 Network Authentication Required")}}
-
The 511 status code indicates that the client needs to authenticate to gain network access.
-
diff --git a/files/id/web/index.html b/files/id/web/index.html deleted file mode 100644 index 9d74fa1a90..0000000000 --- a/files/id/web/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: Teknologi Web untuk Pengembang -slug: Web -tags: - - Landing - - Web -translation_of: Web ---- - - -

Sifat terbuka World Wide Web memberikan kesempatan luar biasa bagi orang-orang yang ingin membuat situs-situs web atau aplikasi daring. Untuk memanfaatkan kemampuan-kemampuan web, Anda perlu belajar cara menggunakannya. Jelajahi link dibawah ini untuk mempelajari lebih lanjut berbagai teknologi web.

- -
-
-

Teknologi-teknologi Web

- -

Dasar-dasar

- -
-
HTML
-
HyperText Markup Language (HTML) adalah bahasa yang digunakan untuk mendeskripsikan dan menentukan konten dari halaman Web.
-
CSS
-
Cascading Style Sheets (CSS) digunakan untuk menentukan tampilan/gambaran konten Web.
-
HTTP
-
HyperText Transfer Protocol (HTTP) digunakan untuk mengantar HTML dan dokumen hypermedia lainnya pada web.
-
- -

Scripting

- -
-
JavaScript
-
JavaScript merupakan bahasa pemrograman yang berjalan di browser Anda. Anda dapat menggunakan untuk menambahkan interaktivitas dan fitur dinamis pada situs web atau aplikasi Anda.
-
Dengan adanya {{glossary("Node.js")}}, Anda juga bisa menjalankan JavaScript pada server.
-
Web APIs
-
Web Aplication Programming Interfaces (Web API) digunakan untuk melaksanakan tugas-tugas beragam, seperti memanipulasi DOM, memainkan audio maupun vidio atau membuat grafis 3D. -
    -
  • Referensi Web API antarmuka semua jenis daftar objek yang Anda dapat gunakan selagi mengembangkan untuk web.
  • -
  • Halaman WebAPI semua daftar komunikasi, akses perangkat keras, dan API lainnya yang dapat Anda gunakan di aplikasi web.
  • -
  • Event reference semua daftar events yang dapat Anda gunakan untuk melacak dan bereaksi pada hal-hal yang menarik yang telah terjadi di halaman web atau aplikasi Anda.
  • -
-
-
Komponen-komponen Web
-
Komponen-komponen web adalah serangkaian teknologi-teknologi berbeda yang memungkinkan Anda untuk membuat elemmen-elemen khusus yang dapat digunakan kembali dengan fungsionalitasnya dienkapsulasi (menjaga elemen didalamnya) jauh dari sisa kode Anda dan menggunakannya di aplikasi web Anda.
-
- -

Grafis

- -
-
Canvas
-
Elemen {{HTMLElement("canvas")}} menyediakan API untuk membuat grafik 2D menggunakan JavaScript.
-
SVG
-
Scalable Vector Graphics (SVG) memungkinkan Anda mengunakan berbagai garis, kurva, dan bentuk-bentuk geometris lainnya untuk membuat grafik. Dengan vektor, Anda dapat membuat gambar yang diubah ukurannya tetap jernih pada ukuran apapun.
-
WebGL
-
WebGL merupakan API JavaScript yang memungkinkan Anda menggambar grafis 3D atau 2D HTML elemen {{HTMLElement("canvas")}}. Teknologi ini memungkinan Anda melihat OpenGL ES standar di konten Web.
-
- -

Audio, vidio, dan multimedia

- -
-
Teknologi-teknologi media Web
-
Sebuah daftar media API terhubung dengan link-link ke dokumentasi yang Anda perlukan masing-masing.
-
Media capture and streams API
-
Referensi untuk API yang memungkinkan untuk streaming, merekam, dan memanipulasi di dua media secara lokal dan seluruh jaringan. Ini termasuk menggunakan kamera lokal dan mikrofon untuk merekam vidio, audio, dan gambar.
-
Menggunakan audio dan vidio HTML
-
Menggabungkan vidio dan/atau audio di sebuah halaman web dan mengendalikan tayangannya.
-
WebRTC
-
RTC di WebRTC singkatan untuk Real-Time Communications, teknologi yang memungkinkan streaming audio/vidio dan berbagi data antara peramban (teman sebaya) klien.
-
- -

Lainnya

- -
-
MathML
-
Mathematical Markup Language (MathML) memungkinkan Anda menampilkan persamaan dan sintaks.
-
XSLT
-
Extensible Stylesheet Language Transformations (XSLT) memungkinan Anda mengubah dokumen XML menjadi HTML yang lebih dapat dibaca manusia.
-
EXSLT
-
Fungsi tambahan yang memungkinkan penambahan fitur ke XSLT.
-
XPath
-
XPath memungkinan Anda memilih node DOM di dokumen menggunakan sintaks kuat daripada penyedianya saat ini oleh CSS selectors.
-
-
- -
-

Ruang Belajar

- -
-
Belajar Pengembangan Web
-
Kumpulan artikel ini menyediakan pemula dengan segala yang mereka butuhkan untuk memulai coding situs web sederhana.
-
Pemroses aplikasi web
-
Pemroses aplikasi web menggunakan modern API bersama dengan strategi peningkatan pemrosesan tradisi untuk membuat aplikasi web berbagai perangkat. Aplikasi ini bekerja dimana saja dan menyediakan beberapa fitur yang memberikan keuntungan pengalaman sesama pengguna sebagai aplikasi asli. Kumupulan set dokumen ini dan panduannya memberikan semua yang kalian perlukan untuk mengetahui tentang PAW.
-
- -

Topik-topik lainnya

- -
-
Aksesbilitas
-
Situs-situs web aksessibel memungkinkan sebanyak-banyaknya orang dapat menggubakan web, termasuk keterbatasan visual, pendengaran, atau kemampuan lainnya. Kumpulan artikel ini menyediakan informasi mengenai pengembangan web aksessibel.
-
Kinerja Web
-
Kinerja Web merupakan seni untuk memastika aplikasi web dimuat cepat dan responsif untuk interaksi pengguna, gak peduli bandwith pengguna, ukuran layar, jaringan, atau kemampuan perangkat.
-
Keamanan
-
Jangan biarkan situs web atau aplikasi Anda kebocoran data ke penjahat. Gunakan kumpulan artikel ini untuk memastikan proyek Anda aman.
-
WebAssembly
-
WebAssembly adalah jenis kode baru yang dapat dijalankan di peramban web — ini merupakan seperti bahasa assembly low-level dengan format compact binary yang berjalan dengan mendekati kinerja asli dan menyediakan bahasa seperti C/C++ dan Rust dengan target kompasi jadi dapat dijalankan di web.
-
-
-
- -

Lihat Semua...

diff --git a/files/id/web/javascript/a_re-introduction_to_javascript/index.html b/files/id/web/javascript/a_re-introduction_to_javascript/index.html deleted file mode 100644 index 5b7ef3b14e..0000000000 --- a/files/id/web/javascript/a_re-introduction_to_javascript/index.html +++ /dev/null @@ -1,862 +0,0 @@ ---- -title: Sebuah pengenalan ulang pada bahasa JavaScript (tutorial JS) -slug: Web/JavaScript/A_re-introduction_to_JavaScript -translation_of: Web/JavaScript/A_re-introduction_to_JavaScript ---- -
{{jsSidebar}}
- -

Pengantar

- -

Mengapa melakukan pengenalan ulang? Karena bahasa {{Glossary("JavaScript")}} terkenal dengan cap buruk sebagai bahasa pemprograman yang paling sering membuat kesalahpahaman di dunia. Sering kali JavaScript diejek sebagai sebuah mainan (layaknya mobil-mobilan) karena terlihat sederhana, tetapi dibalik kesederhanaannya tersebut, terdapat beberapa fitur yang sangat andal. Saat ini JavaScript digunakan oleh aplikasi-aplikasi terkenal dalam jumlah yang luar biasa banyaknya, memiliki pengetahuan yang mendalam tentang teknologi ini adalah salah satu skill penting bagi para pengembang web atau mobile.

- -

Ada baiknya kita memulai pengenalan ini dengan mengetahui sekilas gambaran sejarah dari bahasa pemograman ini. JavaScript dibuat pada tahun 1995 oleh Brendan Eich ketika dia menjadi seorang insinyur perangkat lunak di Netscape. JavaScript dirilis bersamaan dengan Netscape 2 di permulaan tahun 1996. Awalnya JavaScript dinamakan LiveScript, tetapi diganti menjadi JavaScript karena  memanfaatkan ketenaran bahasa pemograman Java dari Sun Microsystem, walaupun keduanya memiliki sedikit sekali kesamaan. Hal inilah yang menjadi sumber kebingungan sejak saat itu.

- -

Beberapa bulan kemudian, Microsoft merilis JScript yang tertanam di dalam Internet Explore 3. Sebagian besar JScript kompatible dan mirip dengan JavaScript. Beberapa bulan setelahnya Netscape mengajukan JavaScript ke  Ecma International, Organisasi Eropa yang melakukan standarisasi sistem informasi dan komunikasi, yang kemudian menghasilkan edisi pertama dari standar {{Glossary("ECMAScript")}} pada tahun itu. Standar ini memperoleh pembaharuan yang signifikan pada ECMAScript edisi ke-3 pada tahun 1999, dan sejak saat itu standar tersebut tidak terlalu banyak mengalami perubahan. Edisi ke-4 ECMAScript diabaikan dengan alasan perbedaan pandangan terhadap kompleksitas bahasa. Beberapa bagian dari edisi ECMAScript ke-4  membentuk dasar ECMAScript edisi ke-5, yang dipublikasi pada tahun 2009 and edisi ECMAScript ke-6 dirilis pada bulan Juni tahun 2015.

- -
-

Karena lebih familiar, mulai dari sini kita akan mengacu ECMAScript sebagai "JavaScript".

-
- -

Tidak seperti kebanyakan bahasa pemograman, JavaScript tidak mempunyai konsep input atau output (I/O). Didesain untuk dapat dieksekusi sebagai bahasa scripting pada lingkungan pengguna dan mekanisme komunikasi dengan dunia luar diserahkan kepada lingkungan pengguna. Browser adalah lingkungan pengguna yang sangat umum, tetapi Interpreter JavaScript dapat juga ditemukan ditempat lain, termasuk Adobe Acrobat, Adobe Photshop, SVG images, Yahoo Widget engine, lingkungan server seperti Node.js, database NoSQL  seperti Apache CouchDB, komputer tertanam, lingkungan desktop seperti GNOME (salah satu antarmuka yang paling terkenal pada sustem operasi GNU/Linux), dan masih banyak lagi yang lainnya.
-  

- -

Ikhtisar

- -

JavaScript adalah bahasa pemograman dinamis berorientasi objek dengan types dan operator, objek bawaan standar (objek literal),  dan methods. Syntax JavaScript dipengaruhi oleh bahasa Java dan C - sangat banyak struktur dalam bahasa tersebut yang digunakan dalam JavaScript. Perbedaan yang paling mendasar adalah JavaScript tidak mempunyai kelas, melainkan fungsionalitas kelas yang dicapai dengan obyek prototipe (Lebih lanjut tentang ES6 {{jsxref("Classes")}}). Perbedaan utama lainnya adalah fungsi sebagai objek, yaitu fungsi mempunyai kapasitas untuk menahan kode yang dapat dieksekusi dan dilewatkan seperti objek yang lain.

- -

Mari mulai dengan melihat blok pembangun dari bahasa pemograman: types (tipe-tipe data). Program pada JavaScript memanipulasi nilai dan nilai tersebut termasuk ke dalam sebuah tipe. Beberapa tipe dalam JavaScript adalah:
-  

- - - -

...ooo, ada lagi {{jsxref("undefined")}} and {{jsxref("null")}} keduanya mempunyai karakteristik yang sedikit ganjil, {{jsxref("Array")}} merupakan objek spesial, {{jsxref("Date")}} dan {{jsxref("RegExp")}} merupakan objek yang dapat digunakan langsung dan untuk lebih tepatnya, fungsi termasuk dalam objek spesial. Jadi, diagramnya kira-kira seperti ini:

- - - -

Ada beberapa tipe {{jsxref("Error")}} bawaan juga, akan lebih memudahkan jika kita mempelajari terlebih dahulu diagram pertama, bagaimanapun juga kita akan membahas tipe - tipe yang telah dituliskan diatas.

- -

Numbers

- -

Menurut spesifikasi, tipe nomer pada JavaScript menggunakan "format IEEE 754 64-bit double-presisi". Hal ini menyebabkan beberapa konsekuensi, diantaranya tidak adanya tipe integer pada JavaScript. Jadi programmer harus agak teliti dengan operasi aritmatika jika sebelumnya berangkat dari C atau Java.
-
- Perlu juga memperhatikan kasus seperti berikut:

- -
0.1 + 0.2 == 0.30000000000000004
-
- -

Dalam praktiknya, nilai integer diperlakukan sebagai int 32-bit, dan beberapa implementasi bahkan menyimpannya demikian (dalam int 32-bit) kecuali diinstruksikan agar nilai tersebut valid sebagai tipe Number namun tidak dalam integer 32-bit. Hal ini mungkin saja penting untuk operasi yang mementingkan ukuran bit.

- -

Standar operasi aritmatika tersedia, seperti penjumlahan, pengurangan, modulus, dan lain-lain. Ada juga Object bawaan yang kami lupa menyebutkannya di awal disebut {{jsxref("Math")}} yang menyediakan fungsi matematika dan konstan:

- -
Math.sin(3.5);
-var circumference = Math.PI * (r + r);
-
- -

Anda dapat mengonversi sebuah string ke integer dengan menggunakan fungsi bawaan  {{jsxref("Global_objeks/parseInt", "parseInt()")}}. Basis konversi dapat ditambahkan sebagai argumen kedua (tidak wajib), namun sebaiknya ditambahkan:

- -
parseInt("123", 10); // 123
-parseInt("010", 10); // 10
-
- -

Pada peramban kuno, string yang diawali dengan "0" diasumsikan sebagai octal (radix 8), namun hal ini tidak lagi menjadi masalah sejak 2013 dan seterusnya. Kecuali Anda sudah yakin mengenai format string-nya, Anda akan mendapatkan hasil mengejutkan pada peramban kuno tersebut:

- -
parseInt("010");  //  8
-parseInt("0x10"); // 16
-
- -

Di sini, kita melihat fungsi {{jsxref("Global_objeks/parseInt", "parseInt()")}} memperlakukan string pertama sebagai oktal karena diawali dengan "0", dan string kedua sebagai hexadecimal karena diawali dengan "0x". Notasi heksadesimal masih ada; hanya oktal yang telah dihapus.

- -

If you want to convert a binary number to an integer, just change the base:

- -
parseInt("11", 2); // 3
-
- -

Similarly, you can parse floating point numbers using the built-in {{jsxref("Global_objeks/parseFloat", "parseFloat()")}} function. Unlike its {{jsxref("Global_objeks/parseInt", "parseInt()")}} cousin, parseFloat() always uses base 10.

- -

You can also use the unary + operator to convert values to numbers:

- -
+ "42";   // 42
-+ "010";  // 10
-+ "0x10"; // 16
-
- -

A special value called {{jsxref("NaN")}} (short for "Not a Number") is returned if the string is non-numeric:

- -
parseInt("hello", 10); // NaN
-
- -

NaN is toxic: if you provide it as an input to any mathematical operation the result will also be NaN:

- -
NaN + 5; // NaN
-
- -

You can test for NaN using the built-in {{jsxref("Global_objeks/isNaN", "isNaN()")}} function:

- -
isNaN(NaN); // true
-
- -

JavaScript also has the special values {{jsxref("Infinity")}} and -Infinity:

- -
 1 / 0; //  Infinity
--1 / 0; // -Infinity
-
- -

You can test for Infinity, -Infinity and NaN values using the built-in {{jsxref("Global_objeks/isFinite", "isFinite()")}} function:

- -
isFinite(1/0); // false
-isFinite(-Infinity); // false
-isFinite(NaN); // false
-
- -
The {{jsxref("Global_objeks/parseInt", "parseInt()")}} and {{jsxref("Global_objeks/parseFloat", "parseFloat()")}} functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.
- -

Strings

- -

Strings in JavaScript are sequences of Unicode characters. This should be welcome news to anyone who has had to deal with internationalization. More accurately, they are sequences of UTF-16 code units; each code unit is represented by a 16-bit number. Each Unicode character is represented by either 1 or 2 code units.

- -

If you want to represent a single character, you just use a string consisting of that single character.

- -

To find the length of a string (in code units), access its length property:

- -
"hello".length; // 5
-
- -

There's our first brush with JavaScript objeks! Did we mention that you can use strings like {{jsxref("objek", "objeks", "", 1)}} too? They have {{jsxref("String", "methods", "#Methods", 1)}} as well that allow you to manipulate the string and access information about the string:

- -
"hello".charAt(0); // "h"
-"hello, world".replace("hello", "goodbye"); // "goodbye, world"
-"hello".toUpperCase(); // "HELLO"
-
- -

Other types

- -

JavaScript distinguishes between {{jsxref("null")}}, which is a value that indicates a deliberate non-value (and is only accessible through the null keyword), and {{jsxref("undefined")}}, which is a value of type undefined that indicates an uninitialized value — that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is undefined. undefined is actually a constant.

- -

JavaScript has a boolean type, with possible values true and false (both of which are keywords.) Any value can be converted to a boolean according to the following rules:

- -
    -
  1. false, 0, empty strings (""), NaN, null, and undefined all become false.
  2. -
  3. All other values become true.
  4. -
- -

You can perform this conversion explicitly using the Boolean() function:

- -
Boolean("");  // false
-Boolean(234); // true
-
- -

However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an if statement (see below.) For this reason, we sometimes speak simply of "true values" and "false values," meaning values that become true and false, respectively, when converted to booleans. Alternatively, such values can be called "truthy" and "falsy", respectively.

- -

Boolean operations such as && (logical and), || (logical or), and ! (logical not) are supported; see below.

- -

Variables

- -

New variables in JavaScript are declared using the var keyword:

- -
var a;
-var name = "simon";
-
- -

If you declare a variable without assigning any value to it, its type is undefined.

- -

An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function. However, starting with ECMAScript Edition 6, let and const declarations allow you to create block-scoped variables.

- -

Operators

- -

JavaScript's numeric operators are +, -, *, / and % — which is the remainder operator (which is not the same as modulo.) Values are assigned using =, and there are also compound assignment statements such as += and -=. These extend out to x = x operator y.

- -
x += 5
-x = x + 5
-
- -

You can use ++ and -- to increment and decrement respectively. These can be used as prefix or postfix operators.

- -

The + operator also does string concatenation:

- -
"hello" + " world"; // "hello world"
-
- -

If you add a string to a number (or other value) everything is converted in to a string first. This might catch you up:

- -
"3" + 4 + 5;  // "345"
- 3 + 4 + "5"; // "75"
-
- -

Adding an empty string to something is a useful way of converting it to a string itself.

- -

Comparisons in JavaScript can be made using <, >, <= and >=. These work for both strings and numbers. Equality is a little less straightforward. The double-equals operator performs type coercion if you give it different types, with sometimes interesting results:

- -
123 == "123"; // true
-1 == true; // true
-
- -

To avoid type coercion and make sure your comparisons are always accurate, you should always use the triple-equals operator:

- -
123 === "123"; // false
-1 === true;    // false
-
- -

There are also != and !== operators.

- -

JavaScript also has bitwise operations. If you want to use them, they're there.

- -

Control structures

- -

JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by if and else; you can chain them together if you like:

- -
var name = "kittens";
-if (name == "puppies") {
-  name += "!";
-} else if (name == "kittens") {
-  name += "!!";
-} else {
-  name = "!" + name;
-}
-name == "kittens!!"
-
- -

JavaScript has while loops and do-while loops. The first is good for basic looping; the second for loops where you wish to ensure that the body of the loop is executed at least once:

- -
while (true) {
-  // an infinite loop!
-}
-
-var input;
-do {
-  input = get_input();
-} while (inputIsNotValid(input))
-
- -

JavaScript's for loop is the same as that in C and Java: it lets you provide the control information for your loop on a single line.

- -
for (var i = 0; i < 5; i++) {
-  // Will execute 5 times
-}
-
- -

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objeks before accessing their attributes:

- -
var name = o && o.getName();
-
- -

Or for setting default values:

- -
var name = otherName || "default";
-
- -

JavaScript has a ternary operator for conditional expressions:

- -
var allowed = (age > 18) ? "yes" : "no";
-
- -

The switch statement can be used for multiple branches based on a number or string:

- -
switch(action) {
-  case 'draw':
-    drawIt();
-    break;
-  case 'eat':
-    eatIt();
-    break;
-  default:
-    doNothing();
-}
-
- -

If you don't add a break statement, execution will "fall through" to the next level. This is very rarely what you want — in fact it's worth specifically labeling deliberate fallthrough with a comment if you really meant it to aid debugging:

- -
switch(a) {
-  case 1: // fallthrough
-  case 2:
-    eatIt();
-    break;
-  default:
-    doNothing();
-}
-
- -

The default clause is optional. You can have expressions in both the switch part and the cases if you like; comparisons take place between the two using the === operator:

- -
switch(1 + 3) {
-  case 2 + 2:
-    yay();
-    break;
-  default:
-    neverhappens();
-}
-
- -

objeks

- -

JavaScript objeks can be thought of as simple collections of name-value pairs. As such, they are similar to:

- - - -

The fact that this data structure is so widely used is a testament to its versatility. Since everything (bar core types) in JavaScript is an objek, any JavaScript program naturally involves a great deal of hash table lookups. It's a good thing they're so fast!

- -

The "name" part is a JavaScript string, while the value can be any JavaScript value — including more objeks. This allows you to build data structures of arbitrary complexity.

- -

There are two basic ways to create an empty objek:

- -
var obj = new objek();
-
- -

And:

- -
var obj = {};
-
- -

These are semantically equivalent; the second is called objek literal syntax, and is more convenient. This syntax is also the core of JSON format and should be preferred at all times.

- -

objek literal syntax can be used to initialize an objek in its entirety:

- -
var obj = {
-  name: "Carrot",
-  "for": "Max",
-  details: {
-    color: "orange",
-    size: 12
-  }
-}
-
- -

Attribute access can be chained together:

- -
obj.details.color; // orange
-obj["details"]["size"]; // 12
-
- -

The following example creates an objek prototype, Person, and instance of that prototype, You.

- -
function Person(name, age) {
-  this.name = name;
-  this.age = age;
-}
-
-// Define an objek
-var You = new Person("You", 24);
-// We are creating a new person named "You"
-// (that was the first parameter, and the age..)
-
- -

Once created, an objek's properties can again be accessed in one of two ways:

- -
obj.name = "Simon";
-var name = obj.name;
-
- -

And...

- -
obj["name"] = "Simon";
-var name = obj["name"];
-
- -

These are also semantically equivalent. The second method has the advantage that the name of the property is provided as a string, which means it can be calculated at run-time. However, using this method prevents some JavaScript engine and minifier optimizations being applied. It can also be used to set and get properties with names that are reserved words:

- -
obj.for = "Simon"; // Syntax error, because 'for' is a reserved word
-obj["for"] = "Simon"; // works fine
-
- -
-

Starting in ECMAScript 5, reserved words may be used as objek property names "in the buff". This means that they don't need to be "clothed" in quotes when defining objek literals. See the ES5 Spec.

-
- -

For more on objeks and prototypes see: objek.prototype.

- -

Arrays

- -

Arrays in JavaScript are actually a special type of objek. They work very much like regular objeks (numerical properties can naturally be accessed only using [] syntax) but they have one magic property called 'length'. This is always one more than the highest index in the array.

- -

One way of creating arrays is as follows:

- -
var a = new Array();
-a[0] = "dog";
-a[1] = "cat";
-a[2] = "hen";
-a.length; // 3
-
- -

A more convenient notation is to use an array literal:

- -
var a = ["dog", "cat", "hen"];
-a.length; // 3
-
- -

Note that array.length isn't necessarily the number of items in the array. Consider the following:

- -
var a = ["dog", "cat", "hen"];
-a[100] = "fox";
-a.length; // 101
-
- -

Remember — the length of the array is one more than the highest index.

- -

If you query a non-existent array index, you'll get a value of undefined returned:

- -
typeof a[90]; // undefined
-
- -

If you take the above into account, you can iterate over an array using the following:

- -
for (var i = 0; i < a.length; i++) {
-  // Do something with a[i]
-}
-
- -

You can iterate over an array using a for...in loop. Note that if someone added new properties to Array.prototype, they will also be iterated over by this loop.  Therefore this method is "not" recommended.

- -

Another way of iterating over an array that was added with ECMAScript 5 is forEach():

- -
["dog", "cat", "hen"].forEach(function(currentValue, index, array) {
-  // Do something with currentValue or array[index]
-});
-
- -

If you want to append an item to an array simply do it like this:

- -
a.push(item);
- -

Arrays come with a number of methods. See also the full documentation for array methods.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Method nameDescription
a.toString()Returns a string with the toString() of each element separated by commas.
a.toLocaleString()Returns a string with the toLocaleString() of each element separated by commas.
a.concat(item1[, item2[, ...[, itemN]]])Returns a new array with the items added on to it.
a.join(sep)Converts the array to a string — with values delimited by the sep param
a.pop()Removes and returns the last item.
a.push(item1, ..., itemN)Adds one or more items to the end.
a.reverse()Reverses the array.
a.shift()Removes and returns the first item.
a.slice(start[, end])Returns a sub-array.
a.sort([cmpfn])Takes an optional comparison function.
a.splice(start, delcount[, item1[, ...[, itemN]]])Lets you modify an array by deleting a section and replacing it with more items.
a.unshift(item1[, item2[, ...[, itemN]]])Prepends items to the start of the array.
- -

Functions

- -

Along with objeks, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:

- -
function add(x, y) {
-  var total = x + y;
-  return total;
-}
-
- -

This demonstrates a basic function. A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like, and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

- -

The named parameters turn out to be more like guidelines than anything else. You can call a function without passing the parameters it expects, in which case they will be set to undefined.

- -
add(); // NaN
-// You can't perform addition on undefined
-
- -

You can also pass in more arguments than the function is expecting:

- -
add(2, 3, 4); // 5
-// added the first two; 4 was ignored
-
- -

That may seem a little silly, but functions have access to an additional variable inside their body called arguments, which is an array-like objek holding all of the values passed to the function. Let's re-write the add function to take as many values as we want:

- -
function add() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum;
-}
-
-add(2, 3, 4, 5); // 14
-
- -

That's really not any more useful than writing 2 + 3 + 4 + 5 though. Let's create an averaging function:

- -
function avg() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum / arguments.length;
-}
-
-avg(2, 3, 4, 5); // 3.5
-
- -

This is pretty useful, but introduces a new problem. The avg() function takes a comma separated list of arguments — but what if you want to find the average of an array? You could just rewrite the function as follows:

- -
function avgArray(arr) {
-  var sum = 0;
-  for (var i = 0, j = arr.length; i < j; i++) {
-    sum += arr[i];
-  }
-  return sum / arr.length;
-}
-
-avgArray([2, 3, 4, 5]); // 3.5
-
- -

But it would be nice to be able to reuse the function that we've already created. Luckily, JavaScript lets you call a function and call it with an arbitrary array of arguments, using the {{jsxref("Function.apply", "apply()")}} method of any function objek.

- -
avg.apply(null, [2, 3, 4, 5]); // 3.5
-
- -

The second argument to apply() is the array to use as arguments; the first will be discussed later on. This emphasizes the fact that functions are objeks too.

- -

JavaScript lets you create anonymous functions.

- -
var avg = function() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum / arguments.length;
-};
-
- -

This is semantically equivalent to the function avg() form. It's extremely powerful, as it lets you put a full function definition anywhere that you would normally put an expression. This enables all sorts of clever tricks. Here's a way of "hiding" some local variables — like block scope in C:

- -
var a = 1;
-var b = 2;
-
-(function() {
-  var b = 3;
-  a += b;
-})();
-
-a; // 4
-b; // 2
-
- -

JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.

- -
function countChars(elm) {
-  if (elm.nodeType == 3) { // TEXT_NODE
-    return elm.nodeValue.length;
-  }
-  var count = 0;
-  for (var i = 0, child; child = elm.childNodes[i]; i++) {
-    count += countChars(child);
-  }
-  return count;
-}
-
- -

This highlights a potential problem with anonymous functions: how do you call them recursively if they don't have a name? JavaScript lets you name function expressions for this. You can use named IIFEs (Immediately Invoked Function Expressions) as shown below:

- -
var charsInBody = (function counter(elm) {
-  if (elm.nodeType == 3) { // TEXT_NODE
-    return elm.nodeValue.length;
-  }
-  var count = 0;
-  for (var i = 0, child; child = elm.childNodes[i]; i++) {
-    count += counter(child);
-  }
-  return count;
-})(document.body);
-
- -

The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging.

- -

Note that JavaScript functions are themselves objeks — like everything else in JavaScript — and you can add or change properties on them just like we've seen earlier in the objeks section.

- -

Custom objeks

- -
For a more detailed discussion of objek-oriented programming in JavaScript, see Introduction to objek Oriented JavaScript.
- -

In classic objek Oriented Programming, objeks are collections of data and methods that operate on that data. JavaScript is a prototype-based language that contains no class statement, as you'd find in C++ or Java (this is sometimes confusing for programmers accustomed to languages with a class statement.) Instead, JavaScript uses functions as classes. Let's consider a person objek with first and last name fields. There are two ways in which the name might be displayed: as "first last" or as "last, first". Using the functions and objeks that we've discussed previously, we could display the data like this:

- -
function makePerson(first, last) {
-  return {
-    first: first,
-    last: last
-  };
-}
-function personFullName(person) {
-  return person.first + ' ' + person.last;
-}
-function personFullNameReversed(person) {
-  return person.last + ', ' + person.first;
-}
-
-s = makePerson("Simon", "Willison");
-personFullName(s); // "Simon Willison"
-personFullNameReversed(s); // "Willison, Simon"
-
- -

This works, but it's pretty ugly. You end up with dozens of functions in your global namespace. What we really need is a way to attach a function to an objek. Since functions are objeks, this is easy:

- -
function makePerson(first, last) {
-  return {
-    first: first,
-    last: last,
-    fullName: function() {
-      return this.first + ' ' + this.last;
-    },
-    fullNameReversed: function() {
-      return this.last + ', ' + this.first;
-    }
-  };
-}
-
-s = makePerson("Simon", "Willison")
-s.fullName(); // "Simon Willison"
-s.fullNameReversed(); // "Willison, Simon"
-
- -

There's something here we haven't seen before: the this keyword. Used inside a function, this refers to the current objek. What that actually means is specified by the way in which you called that function. If you called it using dot notation or bracket notation on an objek, that objek becomes this. If dot notation wasn't used for the call, this refers to the global objek.

- -

Note that this is a frequent cause of mistakes. For example:

- -
s = makePerson("Simon", "Willison");
-var fullName = s.fullName;
-fullName(); // undefined undefined
-
- -

When we call fullName() alone, without using s.fullName(), this is bound to the global objek. Since there are no global variables called first or last we get undefined for each one.

- -

We can take advantage of the this keyword to improve our makePerson function:

- -
function Person(first, last) {
-  this.first = first;
-  this.last = last;
-  this.fullName = function() {
-    return this.first + ' ' + this.last;
-  };
-  this.fullNameReversed = function() {
-    return this.last + ', ' + this.first;
-  };
-}
-var s = new Person("Simon", "Willison");
-
- -

We have introduced another keyword: new. new is strongly related to this. It creates a brand new empty objek, and then calls the function specified, with this set to that new objek. Notice though that the function specified with this does not return a value but merely modifies the this objek. It's new that returns the this objek to the calling site. Functions that are designed to be called by new are called constructor functions. Common practice is to capitalize these functions as a reminder to call them with new.

- -

The improved function still has the same pitfall with calling fullName() alone.

- -

Our person objeks are getting better, but there are still some ugly edges to them. Every time we create a person objek we are creating two brand new function objeks within it — wouldn't it be better if this code was shared?

- -
function personFullName() {
-  return this.first + ' ' + this.last;
-}
-function personFullNameReversed() {
-  return this.last + ', ' + this.first;
-}
-function Person(first, last) {
-  this.first = first;
-  this.last = last;
-  this.fullName = personFullName;
-  this.fullNameReversed = personFullNameReversed;
-}
-
- -

That's better: we are creating the method functions only once, and assigning references to them inside the constructor. Can we do any better than that? The answer is yes:

- -
function Person(first, last) {
-  this.first = first;
-  this.last = last;
-}
-Person.prototype.fullName = function() {
-  return this.first + ' ' + this.last;
-};
-Person.prototype.fullNameReversed = function() {
-  return this.last + ', ' + this.first;
-};
-
- -

Person.prototype is an objek shared by all instances of Person. It forms part of a lookup chain (that has a special name, "prototype chain"): any time you attempt to access a property of Person that isn't set, JavaScript will check Person.prototype to see if that property exists there instead. As a result, anything assigned to Person.prototype becomes available to all instances of that constructor via the this objek.

- -

This is an incredibly powerful tool. JavaScript lets you modify something's prototype at any time in your program, which means you can add extra methods to existing objeks at runtime:

- -
s = new Person("Simon", "Willison");
-s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function
-
-Person.prototype.firstNameCaps = function firstNameCaps() {
-  return this.first.toUpperCase()
-};
-s.firstNameCaps(); // "SIMON"
-
- -

Interestingly, you can also add things to the prototype of built-in JavaScript objeks. Let's add a method to String that returns that string in reverse:

- -
var s = "Simon";
-s.reversed(); // TypeError on line 1: s.reversed is not a function
-
-String.prototype.reversed = function reversed() {
-  var r = "";
-  for (var i = this.length - 1; i >= 0; i--) {
-    r += this[i];
-  }
-  return r;
-};
-
-s.reversed(); // nomiS
-
- -

Our new method even works on string literals!

- -
"This can now be reversed".reversed(); // desrever eb won nac sihT
-
- -

As mentioned before, the prototype forms part of a chain. The root of that chain is objek.prototype, whose methods include toString() — it is this method that is called when you try to represent an objek as a string. This is useful for debugging our Person objeks:

- -
var s = new Person("Simon", "Willison");
-s; // [objek objek]
-
-Person.prototype.toString = function() {
-  return '<Person: ' + this.fullName() + '>';
-}
-
-s.toString(); // "<Person: Simon Willison>"
-
- -

Remember how avg.apply() had a null first argument? We can revisit that now. The first argument to apply() is the objek that should be treated as 'this'. For example, here's a trivial implementation of new:

- -
function trivialNew(constructor, ...args) {
-  var o = {}; // Create an objek
-  constructor.apply(o, args);
-  return o;
-}
-
- -

This isn't an exact replica of new as it doesn't set up the prototype chain (it would be difficult to illustrate). This is not something you use very often, but it's useful to know about. In this snippet, ...args (including the ellipsis) is called the "rest arguments" — as the name implies, this contains the rest of the arguments.

- -

Calling

- -
var bill = trivialNew(Person, "William", "Orange");
- -

is therefore almost equivalent to

- -
var bill = new Person("William", "Orange");
- -

apply() has a sister function named call, which again lets you set this but takes an expanded argument list as opposed to an array.

- -
function lastNameCaps() {
-  return this.last.toUpperCase();
-}
-var s = new Person("Simon", "Willison");
-lastNameCaps.call(s);
-// Is the same as:
-s.lastNameCaps = lastNameCaps;
-s.lastNameCaps();
-
- -

Inner functions

- -

JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier makePerson() function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:

- -
function betterExampleNeeded() {
-  var a = 1;
-  function oneMoreThanA() {
-    return a + 1;
-  }
-  return oneMoreThanA();
-}
-
- -

This provides a great deal of utility in writing more maintainable code. If a function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside the function that will be called from elsewhere. This keeps the number of functions that are in the global scope down, which is always a good thing.

- -

This is also a great counter to the lure of global variables. When writing complex code it is often tempting to use global variables to share values between multiple functions — which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together when it makes sense without polluting your global namespace — "local globals" if you like. This technique should be used with caution, but it's a useful ability to have.

- -

Closures

- -

This leads us to one of the most powerful abstractions that JavaScript has to offer — but also the most potentially confusing. What does this do?

- -
function makeAdder(a) {
-  return function(b) {
-    return a + b;
-  };
-}
-var x = makeAdder(5);
-var y = makeAdder(20);
-x(6); // ?
-y(7); // ?
-
- -

The name of the makeAdder() function should give it away: it creates a new 'adder' functions, which when called with one argument adds it to the argument that they were created with.

- -

What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they do still exist — otherwise the adder functions would be unable to work. What's more, there are two different "copies" of makeAdder()'s local variables — one in which a is 5 and one in which a is 20. So the result of those function calls is as follows:

- -
x(6); // returns 11
-y(7); // returns 27
-
- -

Here's what's actually happening. Whenever JavaScript executes a function, a 'scope' objek is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters. This is similar to the global objek that all global variables and functions live in, but with a couple of important differences: firstly, a brand new scope objek is created every time a function starts executing, and secondly, unlike the global objek (which is accessible as this and in browsers as window) these scope objeks cannot be directly accessed from your JavaScript code. There is no mechanism for iterating over the properties of the current scope objek, for example.

- -

So when makeAdder() is called, a scope objek is created with one property: a, which is the argument passed to the makeAdder() function. makeAdder() then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope objek created for makeAdder() at this point, but the returned function maintains a reference back to that scope objek. As a result, the scope objek will not be garbage collected until there are no more references to the function objek that makeAdder() returned.

- -

Scope objeks form a chain called the scope chain, similar to the prototype chain used by JavaScript's objek system.

- -

A closure is the combination of a function and the scope objek in which it was created. Closures let you save state — as such, they can often be used in place of objeks. You can find several excellent introductions to closures.

diff --git a/files/id/web/javascript/closures/index.html b/files/id/web/javascript/closures/index.html deleted file mode 100644 index 8221ca46e6..0000000000 --- a/files/id/web/javascript/closures/index.html +++ /dev/null @@ -1,346 +0,0 @@ ---- -title: Closures -slug: Web/JavaScript/Closures -translation_of: Web/JavaScript/Closures -original_slug: Web/JavaScript/Panduan/Closures ---- -

Closure adalah fungsi yang merujuk kepada variabel yang mandiri (bebas). 

- -

Dengan kata lain, fungsi yang di definisikan di dalam closure 'mengingat' lingkungan dimana closure ini didefinisikan. 

- -

Lihat contoh berikut:

- -
-
function init() {
-    var name = "Mozilla"; // name adalah sebuah lokal variabel yang dibuat oleh init
-    function displayName() { // displayName() adalah fungsi internal, sebuah closure
-        alert (name); // displayName() menggunakan variabel yang dideklarasikan pada fungsi induknya
-    }
-    displayName();
-}
-init();
-
-
- -

init() membuat sebuah lokal variabel name dan kemudian memanggil fungsi displayName(). displayName() adalah fungsi internal yang didefinisikan didalam init() dan hanya dapat diakses di dalam fungsi tersebut. displayName() tidak memiliki lokal variabelnya sendiri, namun fungsi ini memiliki akses ke variabel diluar fungsinya dan dapat menggunakan variabel name tersebut yang telah di deklarasikan di fungsi induknya.

- -

Jalankan kode dan perhatikan bahwa alert() dapat menampilkan isi dari variabel name, dimana variabel tersebut dideklarasikan pada fungsi induknya. Ini adalah sebuah contoh dari ruang lingkup leksikal (lexical scoping), yang menunjukan bagaimana cara javascript mencari variabel. Di Javascript lokasi dimana variabel tersebut dideklarasikan di dalam source code menentukan dimana variabel itu dapat diakses. Nested functions memiliki akses pada variabel yang dideklarasikan pada ruang lingkup induknya.

- -

Lihat contoh berikut:

- -
function makeFunc() {
-  var name = "Mozilla";
-  function displayName() {
-    alert(name);
-  }
-  return displayName;
-}
-
-var myFunc = makeFunc();
-myFunc();
-
- -

Jika kamu menjalankan kode ini, kode ini akan memiliki efek yang sama seperti contoh sebelumnya init(): teks "Mozilla" akan muncul di JavaScript alert box. Yang membedakan dan menarik adalah fungsi internal displayName() di kembalikan terlebih dahulu ke fungsi di luar sebelum di eksekusi.

- -

Jika dilihat ini agak aneh karena normalnya pada bahasa pemrograman lain, variabel lokal di dalam sebuah fungsi hanya ada saat fungsi tersebut dieksekusi. Sehingga saat makeFunc() selesai dieksekusi, sewajarnya variabel name ini tidak dapat diakses lagi. Namun, karena kode ini masih berjalan normal, ini adalah hal yang berbeda di Javascript.

- -

Alasannya adalah fungsi tersebut telah menjadi closure di javascript. Closure adalah kombinasi dari fungsi dan lingkungan leksikal dimana fungsi itu di deklarasikan. Lingkungan ini terdiri dari lokal variabel yang berada di ruang lingkup yang sama saat closure dibuat. Pada kasus ini, myFunc bereferensi kepada fungsi displayName yang telah dibuat ketika makeFunc dijalankan. Fungsi displayName akan tepat menjaga akses ke lingkungan leksikalnya, dimana variabel name ini aktif. Untuk alasan inilah, ketika myFunc di panggil, variabel name tetap dapat digunakan dan "Mozilla" dikirim ke alert box.

- -

Berikut adalah contoh menarik yang lainnya — fungsi makeAdder :

- -
function makeAdder(x) {
-  return function(y) {
-    return x + y;
-  };
-}
-
-var add5 = makeAdder(5);
-var add10 = makeAdder(10);
-
-console.log(add5(2));  // 7
-console.log(add10(2)); // 12
-
- -

Di contoh ini, kita telah mendefinisikan fungsi makeAdder(x) dengan satu argument x dan mengembalikan sebuah fungsi baru. Fungsi yang dikembalikan membutuhkan satu argumen y, dan mengembalikan jumlah x dan y.

- -

Esensinya, makeAdder adalah fungsi untuk membuat fungsi (function factory) — fungsi ini akan membuat fungsi yang akan menambahkan angka melalui argumen. Pada contoh diatas kita membuat dua fungsi baru — yang satu menambahkan 5 melalui argumentnya dan satu menambahkan 10.

- -

add5 dan add10 keduanya adalah closure. Fungsi ini menggunakan definisi fungsi yang sama, namun menggunakan memori yang berbeda. Di add5 variabel x memiliki nilai 5. sedangkan di add10 variabel x memiliki nilai 10.

- -

Penggunaan Closure

- -

Setelah membaca teorinya muncul pertanyaan —  Apakah closure berguna? Mari kita lihat implikasi dari penggunaan closure. Closure membantu kita mengakses data (pada lingkungannya) dengan fungsi yang mengoperasikan data tersebut. Ini berhubungan dengan object oriented programming, dimana objek obj0ek tersebut membantu kita dalam menghubukan beberapa data (properti objek) dengan satu atau lebih method.

- -

Karena itu, kamu dapat menggunakan closure dimanapun kamu dapat menggunakan objek dengan satu method.

- -

Situasi ini banyak ditemui umumnya pada pengembangan web. Banyak kode yang kita tulis di Javascript berdasarkan event — kita definisikan terlebih dahulu sifat dari event ini, kemudian menempelkannya pada event yang di panggil oleh user (seperti klik atau penekanan tombol). Kode kita secara garis umum adalah sebuah callback: sebuah fungsi yang dijalankan untuk merespon sebuah event.

- -

Berikut adalah contoh: kita ingin menambahkan beberapa tombol di sebuah halaman yang akan merubah ukuran teks. Cara untuk melakukannya adalah dengan menentukan ukuran huruf dari elemen body dalam satuan unit pixel, kemudian menentukan ukuran elemen lain di halaman (seperti header) menggunakan satuan unit em:

- -
body {
-  font-family: Helvetica, Arial, sans-serif;
-  font-size: 12px;
-}
-
-h1 {
-  font-size: 1.5em;
-}
-
-h2 {
-  font-size: 1.2em;
-}
-
- -

Tombol interaktif kita dapat merubah ukuran huruf dari elemen body dan elemen yang lainnya akan menyesuaikan.

- -

Berikut kode Javascript:

- -
function makeSizer(size) {
-  return function() {
-    document.body.style.fontSize = size + 'px';
-  };
-}
-
-var size12 = makeSizer(12);
-var size14 = makeSizer(14);
-var size16 = makeSizer(16);
-
- -

size12, size14, dan size16 adalah fungsi yang akan merubah ukuran teks body ke 12, 14, dan 16 pixel, secara berurutan. Kemudian kita tempelkan fungsi ini ke tombol (pada kasus ini adalah link) sebagai berikut:

- -
document.getElementById('size-12').onclick = size12;
-document.getElementById('size-14').onclick = size14;
-document.getElementById('size-16').onclick = size16;
-
- -
<a href="#" id="size-12">12</a>
-<a href="#" id="size-14">14</a>
-<a href="#" id="size-16">16</a>
-
- -

Lihat pada JSFiddle

- -

Emulating private methods with closures

- -

Languages such as Java provide the ability to declare methods private, meaning that they can only be called by other methods in the same class.

- -

JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures. Private methods aren't just useful for restricting access to code: they also provide a powerful way of managing your global namespace, keeping non-essential methods from cluttering up the public interface to your code.

- -

Here's how to define some public functions that can access private functions and variables, using closures which is also known as the module pattern:

- -
var counter = (function() {
-  var privateCounter = 0;
-  function changeBy(val) {
-    privateCounter += val;
-  }
-  return {
-    increment: function() {
-      changeBy(1);
-    },
-    decrement: function() {
-      changeBy(-1);
-    },
-    value: function() {
-      return privateCounter;
-    }
-  };
-})();
-
-alert(counter.value()); /* Alerts 0 */
-counter.increment();
-counter.increment();
-alert(counter.value()); /* Alerts 2 */
-counter.decrement();
-alert(counter.value()); /* Alerts 1 */
-
- -

There's a lot going on here. In previous examples each closure has had its own environment; here we create a single environment which is shared by three functions: counter.increment, counter.decrement, and counter.value.

- -

The shared environment is created in the body of an anonymous function, which is executed as soon as it has been defined. The environment contains two private items: a variable called privateCounter and a function called changeBy. Neither of these private items can be accessed directly from outside the anonymous function. Instead, they must be accessed by the three public functions that are returned from the anonymous wrapper.

- -

Those three public functions are closures that share the same environment. Thanks to JavaScript's lexical scoping, they each have access to the privateCounter variable and changeBy function.

- -

You'll notice we're defining an anonymous function that creates a counter, and then we call it immediately and assign the result to the counter variable. We could store this function in a separate variable makeCounter and use it to create several counters.

- -
var makeCounter = function() {
-  var privateCounter = 0;
-  function changeBy(val) {
-    privateCounter += val;
-  }
-  return {
-    increment: function() {
-      changeBy(1);
-    },
-    decrement: function() {
-      changeBy(-1);
-    },
-    value: function() {
-      return privateCounter;
-    }
-  }
-};
-
-var counter1 = makeCounter();
-var counter2 = makeCounter();
-alert(counter1.value()); /* Alerts 0 */
-counter1.increment();
-counter1.increment();
-alert(counter1.value()); /* Alerts 2 */
-counter1.decrement();
-alert(counter1.value()); /* Alerts 1 */
-alert(counter2.value()); /* Alerts 0 */
-
- -

Notice how each of the two counters maintains its independence from the other. Its environment during the call of the makeCounter() function is different each time. The closure variable privateCounter contains a different instance each time.

- -

Using closures in this way provides a number of benefits that are normally associated with object oriented programming, in particular data hiding and encapsulation.

- -

Creating closures in loops: A common mistake

- -

Prior to the introduction of the let keyword in JavaScript 1.7, a common problem with closures occurred when they were created inside a loop. Consider the following example:

- -
<p id="help">Helpful notes will appear here</p>
-<p>E-mail: <input type="text" id="email" name="email"></p>
-<p>Name: <input type="text" id="name" name="name"></p>
-<p>Age: <input type="text" id="age" name="age"></p>
-
- -
function showHelp(help) {
-  document.getElementById('help').innerHTML = help;
-}
-
-function setupHelp() {
-  var helpText = [
-      {'id': 'email', 'help': 'Your e-mail address'},
-      {'id': 'name', 'help': 'Your full name'},
-      {'id': 'age', 'help': 'Your age (you must be over 16)'}
-    ];
-
-  for (var i = 0; i < helpText.length; i++) {
-    var item = helpText[i];
-    document.getElementById(item.id).onfocus = function() {
-      showHelp(item.help);
-    }
-  }
-}
-
-setupHelp();
-
- -

Lihat pada JSFiddle

- -

The helpText array defines three helpful hints, each associated with the ID of an input field in the document. The loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method.

- -

If you try this code out, you'll see that it doesn't work as expected. No matter what field you focus on, the message about your age will be displayed.

- -

The reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setupHelp function's scope. Three closures have been created, but each one shares the same single environment. By the time the onfocus callbacks are executed, the loop has run its course and the item variable (shared by all three closures) has been left pointing to the last entry in the helpText list.

- -

One solution in this case is to use more closures: in particular, to use a function factory as described earlier on:

- -
function showHelp(help) {
-  document.getElementById('help').innerHTML = help;
-}
-
-function makeHelpCallback(help) {
-  return function() {
-    showHelp(help);
-  };
-}
-
-function setupHelp() {
-  var helpText = [
-      {'id': 'email', 'help': 'Your e-mail address'},
-      {'id': 'name', 'help': 'Your full name'},
-      {'id': 'age', 'help': 'Your age (you must be over 16)'}
-    ];
-
-  for (var i = 0; i < helpText.length; i++) {
-    var item = helpText[i];
-    document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
-  }
-}
-
-setupHelp();
-
- -

Lihat pada JSFiddle

- -

This works as expected. Rather than the callbacks all sharing a single environment, the makeHelpCallback function creates a new environment for each one in which help refers to the corresponding string from the helpText array.

- -

Performance considerations

- -

It is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.

- -

For instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation).

- -

Consider the following impractical but demonstrative case:

- -
function MyObject(name, message) {
-  this.name = name.toString();
-  this.message = message.toString();
-  this.getName = function() {
-    return this.name;
-  };
-
-  this.getMessage = function() {
-    return this.message;
-  };
-}
-
- -

The previous code does not take advantage of the benefits of closures and thus could instead be formulated:

- -
function MyObject(name, message) {
-  this.name = name.toString();
-  this.message = message.toString();
-}
-MyObject.prototype = {
-  getName: function() {
-    return this.name;
-  },
-  getMessage: function() {
-    return this.message;
-  }
-};
-
- -

However, redefining the prototype is not recommended, so the following example is even better because it appends to the existing prototype:

- -
function MyObject(name, message) {
-  this.name = name.toString();
-  this.message = message.toString();
-}
-MyObject.prototype.getName = function() {
-  return this.name;
-};
-MyObject.prototype.getMessage = function() {
-  return this.message;
-};
-
- -

In the two previous examples, the inherited prototype can be shared by all objects and the method definitions need not occur at every object creation. See Details of the Object Model for more details.

- -

Expression closures

- -

This addition is nothing more than a shorthand for writing simple functions, giving the language something similar to a typical Lambda notation.

- -

JavaScript 1.7 and older:

- -
function(x) { return x * x; }
- -

JavaScript 1.8:

- -
function(x) x * x
- -

This syntax allows you to leave off the braces and 'return' statement - making them implicit. There is no added benefit to writing code in this manner, other than having it be syntactically shorter.

- -

Examples:

- -

A shorthand for binding event listeners:

- -
 document.addEventListener("click", function() false, true);
-
- -

Using this notation with some of the array functions from JavaScript 1.6:

- -
elems.some(function(elem) elem.type == "text");
diff --git a/files/id/web/javascript/data_structures/index.html b/files/id/web/javascript/data_structures/index.html deleted file mode 100644 index 0fba9dc3a5..0000000000 --- a/files/id/web/javascript/data_structures/index.html +++ /dev/null @@ -1,267 +0,0 @@ ---- -title: JavaScript data types and data structures -slug: Web/JavaScript/Data_structures -tags: - - JavaScript - - Tipe -translation_of: Web/JavaScript/Data_structures ---- -

 {{jsSidebar("More")}}

- -

Semua bahasa pemrograman memiliki struktur data bawaan, namun hal tersebut sering dijumpai berbeda antara satu bahasa dengan bahasa lainya. Artikel ini mencoba untuk membuat daftar struktur data bawaan yang tersedia di JavaScript dan sifat-sifat apa saja yang dimiliki. Struktur data bawaan dapat digunakan untuk membangun struktur data lainnya. Bila memungkinkan, perbandingan dengan bahasa lainya akan diambil.

- -

Dynamic typing

- -

JavaScript adalah salah satu bahasa pemrograman yang tidak mengutamakan tipe data. Tidak perlu mendeklarasikan jenis data dari suatu variabel setiap saat. Tipe data akan dideklarasikan secara otomatis diawal program dijalankan. Dengan kata lain memungkinkan untuk menggunakan nama peubah yang sama dengan jenis data yang berbeda:

- -
var foo = 42;    // foo saat ini adalah angka
-foo     = 'bar'; // foo saat ini adalah string
-foo     = true;  // foo saat ini adalah boolean
-
- -

Tipe Data

- -

Standar ECMAScript terakhir menjelaskan tujuh tipe data:

- - - -

Nilai Primitif

- -

Semua tipe kecuali objek menentukan nilai tetap (nilai, yang tidak dapat diubah). Misalnya dan tidak seperti C, Strings tidak dapat diubah. Di JavaScript, string termasuk sebagai nilai primitif.

- -

Undefined

- -

Variabel yang nilainya tidak ditetapkan (tidak diisi) memiliki nilai undefined. Lihat {{jsxref("undefined")}} dan {{Glossary("Undefined")}} untuk lebih lanjut.

- -

Null

- -

Null hanya memiliki sebuah nilai dan terdiri nilai itu sendiri: null. Lihat {{jsxref("null")}} dan {{Glossary("Null")}} untuk lebih lanjut.

- -

Boolean

- -

Merepresentasikan entitas logika dan hanya memiliki dua nilai atau kemungkinan, yaitu: true dan false.

- -

Number

- -

Berdasarkan standar ECMAScript, dikatakan bahwa hanya ada satu tipe nomor, yaitu double-precision 64-bit binary format IEEE 754 value (nomor diantara -(253 -1) dan (253 -1) ). Tidak ada penomoran bilangan bulat yang spesifik. Sebagai tambahan untuk menampilkan bilangan floating-point (bilangan pecahan float), tipe nomor memiliki tiga simbol, yaitu: +Infinity, -Infinity, dan NaN (Not-a-Number)

- -

Untuk memeriksa nomor paling besar atau paling kecil diantara +/-Infinity diatas, dapat menggunakan konstanta {{jsxref("Number.MAX_VALUE")}} atau {{jsxref("Number.MIN_VALUE")}}. Semenjak standar ECMAScript 2015, untuk memeriksa nilai double-precision floating-point dapat menggunakan {{jsxref("Number.isSafeInteger()")}} yang setara dengan {{jsxref("Number.MAX_SAFE_INTEGER")}} dan {{jsxref("Number.MIN_SAFE_INTEGER")}}. Lebih dari batas tersebut, bilangan bulat di JavaScript tidak aman dan akan digantikan dengan perkiraan double-precision floating-point.

- -

Angka 0 merupakan bilangan bulat integer yang memiliki dua representasi, yaitu +0 dan -0 dan pada kenyataannya tidak berpengaruh dalam perhitungan karena jika keduanya dibandingkan akan bernilai benar: +0 === -0 //-->(true) dan akan diberitahu jika pembagi merupakan nol:

- -
> 42 / +0
-Infinity
-> 42 / -0
--Infinity
-
- -

Meskipun angka sering hanya mewakili nilainya, JavaScript menyediakan beberapa operator biner (bitwise) yang dapat digunakan untuk bit masking, yaitu mewakili beberapa nilai Boolean dalam sebuah nomor. Namun, ini biasanya dianggap sebagai praktik yang buruk, karena JavaScript menawarkan cara lain untuk mewakili satu set Boolean (seperti array Boolean atau objek dengan nilai Boolean yang ditetapkan untuk properti bernama). Bit masking juga cenderung membuat kode lebih sulit dibaca, dipahami, dan dirawat. Mungkin diperlukan untuk digunakan di lingkungan yang sangat terbatas, seperti saat mencoba mengatasi kompresi atau dalam kasus ekstrim ketika setiap bit di atas jumlah jaringan. Teknik ini hanya harus dipertimbangkan ketika tidak ada cara terakhir yang dapat diambil untuk mengoptimalkan ukuran.

- -

String

- -

Tipe {{jsxref("Global_Objects/String", "String")}} digunakan untuk menampilkan data tulisan (teks). Terdiri dari beberapa bagian karakter yang dibentuk dari bilangan 16-bit unsigned integer. Setiap karakter pada String menempati posisi pada String. Karakter pertama pada string berindeks 0, kemudian 1, lalu 2, ..., hingga karakter terakhir dari String. Panjang String merupakan jumlah karakter pembentuknya.

- -

Berbeda dengan bahasa pemrogramman C, JavaScript string tidak dapat diubah. Dengan kata lain sekali String dibuat, maka tidak mungkin untuk mengubahnya. Namun memungkinkan untuk membuat String baru berdasarkan operasi string sebelumnya. Contoh:

- - - -

Hati-hati pada "stringly-typing" kode!

- -

String dapat digunakan untuk menampilkan data kompleks (rumit). Keuntungan untuk jangka pendek:

- - - -

Dengan adanya konversi, string dapat menampung semua tipe data, dan hentu bukan hal yang baik. Sebagai contoh, dengan separator (pemisah), string dapat meniru list (pada JavaScript disebut sebagai array). Sayangnya saat pemisah digunakan di salahsatu bagian "list" maka strukturnya akan rusak. Escape character menjadi salahsatu cara untuk menangani hal tersebut. Hal tersebut membutuhkan konversi mahal dan hanya menambah beban pemeliharaan.

- -

Gunakan string untuk data teks. Parse string dan gunakan abstraksi yang tepat jika untuk menampilkan data yang rumit.

- -

Symbol

- -

Baru diperkenalkan sejak JavaScript ECMAScript 2015. Simbol memiliki ciri khas (unik) dan nilai primitif tetap (immutable) serta dapat digunakan sebagai kunci dari properti sebuah Objek. Pada beberapa bahasa pemrogramman, Simbol disebut sebagai atom. Untuk lebih jelasnya, lihat pustaka {{Glossary("Symbol")}} dan pembungkus {{jsxref("Symbol")}} objek di JavaScript.

- -

Objek

- -

Pada ilmu komputer, objek adalah nilai pada memori yang dimungkinkan dialamatkan oleh {{Glossary("Identifier", "identifier")}}.

- -

Properties

- -

Pada JavaScript, objek dapat digambarkan sebagai kumpulan properti. Dengan adanya sintaks objek literal, set properti dibatasi; kemudian properti dapat ditambahkan atau dihapus. Nilai dari properti dapat berupa "nilai" atau tipe data lain, termasuk objek itu sendiri, yang memungkinkan untuk membangun struktur data yang rumit. Properti diidentifikasi menggunakan nilai kunci. Kunci dapat berupa String ataupun Simbol.

- -

Terdapat dua tipe objek properti yang memiliki attribut: data property dan accessor property.

- -

Data Property

- -

mengkaitkan kunci dengan nilai dan memiliki beberapa atribut:

- -

 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AttributTipeKeteranganNilai bawaan
[[Value]]Semua jenis JavaScriptNilai yang diterima dengan mengambil akses properti.undefined
[[Writable]]BooleanJika false, maka propeti [[Value]] tidak dapat diubah.false
[[Enumerable]]BooleanJika true, properti dapat terbaca saat for...in loops. Lihat juga Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanJika false, properti tidak dapat dihapus, tidak dapat diubah menjadi aksesor propeti, juga atribut selain [[Value]] dan [[Writable]] tidak dapat diubah.false
- -

 

- - - - - - - - - - - - - - - - - - - - - - - - - -
Atribut usang (as of ECMAScript 3, renamed in ECMAScript 5)
AtributTipeKeterangan
Read-onlyBooleanDiubah di ES5 menjadi atribut [[Writable]].
DontEnumBooleanDiubah di ES5 menjadi atribut [[Enumerable]].
DontDeleteBooleanDiubah di ES5 menjadi atribut [[Configurable]].
- -

 

- -
-

Note: Biasanya atribut digunakan oleh JavaScript engine, sehingga tidak dapat diakses secara langsung (lihat Object.defineProperty()). Itulah mengapa atribut ditulis dengan kurung siku ganda.

-
- -

 

- -

"Normal" objects, and functions

- -

A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s) and values can be anything. This makes objects a natural fit for hashmaps.

- -

Functions are regular objects with the additional capability of being callable.

- -

Dates

- -

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

- -

Indexed collections: Arrays and typed Arrays

- -

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push(adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

- -

Typed Arrays are new to JavaScript with ECMAScript 2015 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:

- -

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}

- -

Keyed collections: Maps, Sets, WeakMaps, WeakSets

- -

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

- -

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

- -

Usually, to bind data to a DOM node, one could set properties directly on the object or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

- -

Structured data: JSONBagian

- -

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

- -

More objects in the standard libraryBagian

- -

JavaScript has a standard library of built-in objects. Please have a look at the referenceto find out about more objects.

- -

Determining types using the typeofoperator

- -

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}} 
{{SpecName('ES2015', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}} 
- -

See also

- - - -

 

- -

 

diff --git a/files/id/web/javascript/guide/grammar_and_types/index.html b/files/id/web/javascript/guide/grammar_and_types/index.html deleted file mode 100644 index 78eec69d04..0000000000 --- a/files/id/web/javascript/guide/grammar_and_types/index.html +++ /dev/null @@ -1,649 +0,0 @@ ---- -title: Tata Bahasa dan Tipe -slug: Web/JavaScript/Guide/Grammar_and_types -tags: - - JavaScript - - Panduan -translation_of: Web/JavaScript/Guide/Grammar_and_types -original_slug: Web/JavaScript/Panduan/Values,_variables,_and_literals ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
- -

Pada bagian ini membahas tata bahasa dasar Javascript, deklarasi variabel, tipe data dan literal.

- -

Dasar

- -

Sebagian besar sintak JavaScript terinspirasi dari Java, namun juga dipengaruhi oleh Awk, Perl dan Python.

- -

JavaScript bersifat case-sensitive dan menggunakan set karakter Unicode.

- -

Dalam JavaScript, instruksi disebut {{Glossary ("Statement", "pernyataan")}} dan dipisahkan oleh titik koma (;). Spasi, tab dan karakter baris baru disebut whitespace.Teks sumber skrip JavaScript dipindai dari kiri ke kanan dan diubah menjadi urutan elemen masukan yang merupakan token, karakter kontrol, terminator baris, komentar atau whitespace. ECMAScript juga mendefinisikan kata kunci dan literal tertentu dan memiliki aturan untuk penyisipan titik koma secara otomatis (ASI) untuk mengakhiri pernyataan. Namun, dianjurkan untuk selalu menambahkan titik koma untuk mengakhiri pernyataan anda; Itu akan terhindar dari efek samping. Untuk informasi lebih lanjut, lihat referensi rinci tentang tata bahasa eksikal JavaScript.

- -


- Komentar

- -

Sintak komentar pada JavaScript sama dengan C++ dan dalam banyak bahasa pemrograman lainnya:

- -
// komentar satu baris
-
-/* Ini lebih panjang
-   komentar beberapa baris
- */
-
-/* Anda tidak bisa menggunakannya, /* komentar bersarang */ Sintak bermasalah */
- -

Deklarasi

- -

Ada tiga macam deklarasi pada JavaScript.

- -
-
var
-
Mendeklarasikan sebuah variabel, opsional menginisialisasi sebuah nilai.
-
let
-
Mendeklarasikan lingkup-blok, variabel lokal, opsional menginisialisasi sebuah nilai.
-
const
-
Mendeklarasikan sebuah lingkup-blok, baca-saja dinamakan konstanta.
-
- -

Variabel

- -

Anda menggunakan variabel sebagai nama simbolik dalam aplikasi Anda.  Nama variabel, disebut {{Glossary("Identifier", "Pengidentifikasi")}}, sesuai dengan peraturan tertentu.

- -

Pengindetifikasi pada JavaScript harus dimulai dengan huruf, garis bawah (_), atau tanda dolar ($); Karakter selanjutnya bisa berupa digit (0-9). karena JavaScript sensitif huruf (case-sensitive), Huruf termasuk karakter "A" sampai "Z" (huruf besar) dan huruf "a" sampai "z" (huruf kecil) .

- -

Anda dapat menggunakan sebagian besar huruf ISO 8859-1 atau Unicode seperti å dan ü dalam pengidentifikasi (untuk lebih jelasnya lihat postingan blog ini). Anda juga dapat menggunakan urutan rangkaian pelolosan/escape Unicode sebagai karakter dalam pengidentifikasi.

- -

Beberapa contoh nama legal adalah Number_hitstemp99, $credit, dan _name.

- -

Mendeklarasikan variabel

- -

Anda bisa mendeklarasikan sebuah variabel dalam tiga cara:

- - - -

Mengevaluasi variabel

- -

Variabel yang dideklarasikan dengan menggunakan pernyataan  var atau let tanpa penetapan nilai yang ditentukan memiliki nilai undefined.

- -

Upaya untuk mengakses variabel yang tidak dideklarasikan akan menuju kepada pelemparan eksepsi ReferenceError:

- -
var a;
-console.log('Nilai dari a adalah ' + a); // Nilai dari a adalah undefined
-
-console.log('Nilai dari b adalah ' + b); // Nilai dari b adalah undefined
-var b;
-
-console.log('Nilai dari c adalah ' + c); // Tidak tertangkap ReferenceError: c tidak di definisikan
-
-let x;
-console.log('Nilai dari x adalah ' + x); // Nilai dari x adalah undefined
-
-console.log('Nilai dari y adalah ' + y); // Tidak tertangkap ReferenceError: y tidak di definisikan
-let y;
- -

Anda dapat menggunakan undefined untuk menentukan apakah sebuah variabel memiliki nilai. Dalam kode berikut, variabel input tidak diberi nilai, dan pernyataan  if dievaluasi true.

- -
var input;
-if (input === undefined) {
-  lakukanIni();
-} else {
-  lakukanItu();
-}
- -

Nilai  undefined berperilaku sebagai false bila digunakan dalam konteks boolean. Misalnya, kode berikut menjalankan fungsi fungsiSaya karena elemen  myArray undefined:

- -
var myArray = [];
-if (!myArray[0]) fungsiSaya();
- -

Nilai  undefined mengkonversi ke NaN bila digunakan dalam konteks numerik.

- -
var a;
-a + 2;  // Dievaluasi ke NaN
- -

Ketika Anda mengevaluasi sebuah variabel null, nilai null berperilaku seperti 0 dalam konteks numerik dan sebagai false dalam konteks boolean. Sebagai contoh:

- -
var n = null;
-console.log(n * 32); // Akan log 0 ke konsol
- -

Lingkup variabel

- -

Bila Anda mendeklarasikan variabel di luar fungsi apa pun, ini disebut variabel global , karena tersedia pada kode lain dalam dokumen tersebut. Ketika Anda mendeklarasikan sebuah variabel dalam suatu fungsi, itu disebut variabel lokal , karena hanya tersedia di dalam fungsi itu.

- -

JavaScript sebelum ECMAScript 2015 tidak memiliki lingkup pernyataan blok ; Sebaliknya, variabel yang dinyatakan dalam blok bersifat lokal terhadap fungsi (atau lingkup global) yang berada di blok. Misalnya kode berikut akan log 5, karena ruang lingkupnya adalah fungsi (atau konteks global) yang dideklarasikan, bukan bloknya, yang dalam hal ini adalah sebuah pernyataan if.

- -
if (true) {
-  var x = 5;
-}
-console.log(x);  // x is 5
- -

Perilaku ini berubah, saat menggunakan deklarasi let yang diperkenalkan di ECMAScript 2015.

- -
if (true) {
-  let y = 5;
-}
-console.log(y);  // ReferenceError: y tidak di definisikan
- -

Hoisting variabel

- -

Hal lain yang tidak biasa tentang variabel dalam JavaScript adalah Anda bisa merujuk ke variabel yang dideklarasikan nanti, tanpa mendapatkan eksepsi. Konsep ini dikenal sebagai hoistingVariabel dalam JavaScript dalam arti "dikibarkan" atau diangkat ke atas fungsi atau pernyataan. Bagaimanapun, variabel yang dikibarkan akan memberikan nilai undefinedJadi, bahkan jika Anda mendeklarasikan dan menginisialisasi setelah Anda menggunakan atau merujuk ke variabel ini, itu akan tetap memberikan undefined.

- -
/**
- * Contoh 1
- */
-console.log(x === undefined); // true
-var x = 3;
-
-/**
- * Contoh 2
- */
-// Akan memberikan nilai undefined
-var myvar = 'my value';
-
-(function() {
-  console.log(myvar); // undefined
-  var myvar = 'local value';
-})();
- -

Contoh di atas akan dinterprestasikan sama dengan:

- -
/**
- * Contoh 1
- */
-var x;
-console.log(x === undefined); // true
-x = 3;
-
-/**
- * Example 2
- */
-var myvar = 'my value';
-
-(function() {
-  var myvar;
-  console.log(myvar); // undefined
-  myvar = 'nilai lokal';
-})();
- -

Karena hoisting, semua pernyataan var dalam suatu fungsi harus ditempatkan sedekat mungkin ke atas fungsi. Praktik terbaik ini meningkatkan kejelasan kode.

- -

Dalam ECMAScript 2015, variabel  let (const) tidak akan hoist ke bagian atas blok. Bagaimanapun, referensi variabel di blok sebelum deklarasi variabel menghasilkan sebuah ReferenceErrorVariabel ini berada dalam "zona mati temporal" dari awal blok sampai deklarasi diproses.

- -
console.log(x); // ReferenceError
-let x = 3;
- -

Hoisting fungsi

- -

Untuk fungsi, hanya deklarasi fungsi yang diangkat ke atas dan bukan ekspresi fungsi.

- -
/* Deklarasi fungsi */
-
-foo(); // "bar"
-
-function foo() {
-  console.log('bar');
-}
-
-
-/* Ekspresi fungsi */
-
-baz(); // TypeError: baz adalah bukan fungsi
-
-var baz = function() {
-  console.log('bar2');
-};
- -

Variabel global

- -

Variabel global sebenarnya adalah properti dari objek global . Di halaman web objek global itu window, sehingga Anda bisa mengatur dan mengakses variabel global dengan menggunakan sintaks window.variable

- -

Akibatnya, Anda dapat mengakses variabel global yang dideklarasikan dalam satu window atau frame dari window atau frame lain dengan menentukan nama window atau frame. Misalnya, jika variabel yang disebut phoneNumber dinyatakan dalam dokumen, Anda dapat merujuk variabel ini dari iframe as parent.phoneNumber.

- -

Konstanta

- -

Anda bisa membuat variabel baca-saja, dinamai dengan kata kunci constSintaksis dari pengenal konstanta sama dengan pengenal variabel: ia harus dimulai dengan huruf, garis bawah atau tanda dolar ($) dan dapat berisi karakter abjad, numerik, atau garis bawah.

- -
const PI = 3.14;
- -

Konstanta tidak dapat mengubah nilai melalui penugasan atau dinyatakan ulang saat naskah dijalankan. Ini harus diinisialisasi ke sebuah nilai.

- -

Aturan lingkup untuk konstanta sama dengan variabel lingkup-blok let . Jika kata kunci  const dihilangkan, pengenal dianggap mewakili variabel.

- -

Anda tidak dapat mendeklarasikan konstanta dengan nama yang sama dengan fungsi atau variabel dalam lingkup yang sama. Sebagai contoh:

- -
// INI AKAN MENYEBABKAN ERROR
-function f() {};
-const f = 5;
-
-// INI AKAN MENYEBABKAN ERROR JUGA
-function f() {
-  const g = 5;
-  var g;
-
-  //pernyataan
-}
- -

Namun, properti objek yang ditugaskan pada konstanta tidak terlindungi, jadi pernyataan berikut dijalankan tanpa masalah.

- -
const MY_OBJECT = {'key': 'value'};
-MY_OBJECT.key = 'otherValue';
- -

Struktur dan tipe data

- -

Tipe data

- -

Standar ECMAScript terbaru mendefinisikan tujuh tipe data:

- - - -

Meskipun tipe data ini jumlahnya relatif kecil, namun memungkinkan Anda untuk melakukan fungsi-fungsi yang berguna dengan aplikasi Anda.  {{jsxref("Object", "Objects")}} dan {{jsxref("Function", "functions")}} merupakan unsur fundamental lainnya dalam bahasa ini. Anda bisa memikirkan objek sebagai wadah bernama untuk nilai, dan fungsi sebagai prosedur yang dapat dilakukan aplikasi Anda.

- -

Konversi tipe data

- -

JavaScript adalah bahasa yang diketik secara dinamis. Itu berarti Anda tidak perlu menentukan tipe data variabel saat Anda menyatakannya, dan tipe data akan dikonversi secara otomatis sesuai kebutuhan selama eksekusi skrip. Jadi, misalnya, Anda bisa mendefinisikan variabel sebagai berikut:

- -
var jawaban = 42;
- -

Dan nanti, Anda bisa menetapkan variabel yang sama dengan nilai string, misalnya:

- -
jawaban = 'Thanks for all the fish...';
- -

Karena JavaScript diketik secara dinamis, penugasan ini tidak menyebabkan pesan kesalahan.

- -

Dalam ekspresi yang melibatkan nilai numerik dan string dengan operator +, JavaScript mengubah nilai numerik menjadi string. Misalnya, perhatikan pernyataan berikut:

- -
x = 'Jawabannya adalah ' + 42 // "Jawabannya adalah 42"
-y = 42 + ' Adalah jawabannya' // "42 Adalah jawabannya"
- -

Dalam pernyataan yang melibatkan operator lain, JavaScript tidak mengubah nilai numerik menjadi string. Sebagai contoh:

- -
'37' - 7 // 30
-'37' + 7 // "377"
- -

Mengubah string menjadi angka

- -

Dalam kasus yang sebuah nilai mewakili bilangan ada dalam memori sebagai string, ada metode untuk konversi.

- - - -

parseInt Hanya akan memberikan bilangan bulat, jadi penggunaannya berkurang untuk desimal. Selain itu, praktik terbaik untuk parseInt selalu menyertakan parameter radix. Parameter radix digunakan untuk menentukan sistem numerik yang akan digunakan.

- -

Metode alternatif untuk mengambil nomor dari string adalah dengan operator +  (unary plus):

- -
'1.1' + '1.1' = '1.11.1'
-(+'1.1') + (+'1.1') = 2.2
-// Catatan: kurung siku buka tutup ditambahkan untuk kejelasan, tidak diminta.
- -

Literal

- -

Anda menggunakan literal untuk mewakili nilai dalam JavaScript. Ini adalah nilai tetap, bukan variabel, yang Anda berikan secara literal dalam skrip Anda. Bagian ini menjelaskan jenis literal berikut:

- - - -

Literal array

- -

Sebuah literal array adalah daftar dari nol atau lebih ekspresi,  yang masing-masing mewakili elemen array, dilampirkan dalam tanda kurung siku ([]). Bila Anda membuat array menggunakan literal array, ini diinisialisasi dengan nilai yang ditentukan sebagai elemennya, dan panjangnya diatur ke jumlah argumen yang ditentukan.

- -

Contoh berikut membuat array coffees dengan tiga elemen dan panjang tiga:

- -
var coffees = ['French Roast', 'Colombian', 'Kona'];
- -

Catatan: Sebuah literal array  adalah tipe dari object initializer. Lihat Menggunakan Penginisialisasi Objek.

- -

Jika sebuah array dibuat menggunakan literal dalam skrip tingkat-atas, JavaScript menginterpretasikan array setiap kali mengevaluasi ekspresi yang berisi literal array. Selain itu, literal yang digunakan dalam suatu fungsi dibuat setiap kali fungsi dipanggil.

- -

Array literal juga objek ArrayLihat Array dan Koleksi diIndek untuk rincian tentang objek Array.

- -

Ekstra koma dalam literal array

- -

Anda tidak perlu menentukan semua elemen dalam literal array. Jika Anda memasukkan dua koma berturut-turut, array dibuat undefined untuk elemen yang tidak ditentukan. Contoh berikut membuat array fish:

- -
var fish = ['Lion', , 'Angel'];
- -

Array ini memiliki dua elemen dengan nilai dan satu elemen kosong (fish[0] adalah "Lion", fish[1] adalah undefined, dan fish[2] merupakan "Angel").

- -

Jika Anda menyertakan koma di akhir daftar elemen, koma diabaikan. Pada contoh berikut, panjang array adalah tiga. Tidak ada myList[3]Semua koma lainnya dalam daftar menunjukkan elemen baru.

- -

Catatan: Koma diakhir dapat membuat kesalahan pada versi browser lama dan merupakan praktik terbaik untuk menghapusnya.

- -
var myList = ['home', , 'school', ];
- -

Dalam contoh berikut, panjang array adalah empat, dan myList[0]dan myList[2] hilang.

- -
var myList = [ ,'home', , 'school'];
- -

Dalam contoh berikut, panjang array adalah empat, dan myList[1]dan myList[3] hilang. Hanya koma terakhir yang diabaikan.

- -
var myList = ['home', , 'school', , ];
- -

Memahami perilaku ekstra  koma penting untuk memahami JavaScript sebagai bahasa, namun saat menulis kode Anda sendiri: secara eksplisit menyatakan elemen yang hilang sebagai undefined akan meningkatkan kejelasan dan perawatan kode anda.

- -

Literal boolean

- -

Tipe Boolean memiliki dua nilai literal: true dan false.

- -

Jangan membingungkan nilai Boolean primitif true dan false dengan nilai true dan false objek Boolean. Objek Boolean adalah pembungkus di sekitar tipe data Boolean primitif. Lihat {{jsxref("Boolean")}} untuk informasi lebih lanjut.

- -

Integer

- -

Integer dapat dinyatakan dalam desimal (basis 10), heksadesimal (basis 16), oktal (basis 8) dan biner (basis 2).

- - - -

Beberapa contoh literal bilangan bulat adalah:

- -
0, 117 and -345 (desimal, basis 10)
-015, 0001 and -0o77 (oktal, basis 8)
-0x1123, 0x00111 and -0xF1A7 (heksadesimal, "hex" or basis 16)
-0b11, 0b0011 and -0b11 (biner, basis 2)
- -

Untuk informasi lebih lanjut, lihat literatur numerik dalam referensi tata bahasa leksikal .

- -

Literal floating-point

- -

Sebuah literal  floating-point dapat memiliki bagian berikut:

- - - -

Bagian eksponennya adalah "e" atau "E" diikuti oleh bilangan bulat, yang dapat ditandatangani (didahului dengan "+" atau "-"). Literal floating-point harus memiliki setidaknya satu digit dan titik desimal atau "e" (atau "E").

- -

Lebih ringkas lagi, sintaksnya adalah:

- -
[(+|-)][angka][.angka][(E|e)[(+|-)]angka]
- -

Sebagai contoh:

- -
3.1415926
--.123456789
--3.1E+12
-.1e-23
- -

Literal objek

- -

Literal objek adalah daftar dari nol atau lebih pasangan nama properti dan nilai objek yang terkait, yang dilampirkan dalam kurung kurawal ({}). Anda seharusnya tidak menggunakan literal objek di awal sebuah pernyataan. Ini akan menyebabkan kesalahan atau tidak berperilaku seperti yang Anda harapkan, karena { akan ditafsirkan sebagai awal dari sebuah blok.

- -

Berikut ini adalah contoh dari literal objek. Elemen pertama dari objek car mendefinisikan sebuah properti myCar, dan menetapkan sebuah string baru, " Saturn";  Elemen kedua, properti getCar,  segera diberi hasil pemanggilan function (carTypes("Honda")); elemen ketiga, properti special menggunakan variabel yang ada ( sales).

- -
var sales = 'Toyota';
-
-function carTypes(name) {
-  if (name === 'Honda') {
-    return name;
-  } else {
-    return "Maaf, kami tidak menjual " + name + ".";
-  }
-}
-
-var car = { myCar: 'Saturn', getCar: carTypes('Honda'), special: sales };
-
-console.log(car.myCar);   // Saturn
-console.log(car.getCar);  // Honda
-console.log(car.special); // Toyota
- -

Selain itu, Anda dapat menggunakan literal numerik atau string untuk nama properti atau menyarangkan objek di dalam objek yang lain. Contoh berikut menggunakan opsi ini.

- -
var car = { manyCars: {a: 'Saab', 'b': 'Jeep'}, 7: 'Mazda' };
-
-console.log(car.manyCars.b); // Jeep
-console.log(car[7]); // Mazda
- -

Nama properti objek bisa berupa string apapun, termasuk string kosong. Jika nama properti akan menjadi {{Glossary("Identifier","pengidentifikasi")}} JavaScript yang tidak valid atau angka, maka harus dilampirkan dalam tanda petik. Nama properti yang pengidentifikasi tidak valid juga tidak dapat diakses sebagai properti dot (.), namun dapat diakses dan ditetapkan dengan notasi seperti array ("[]").

- -
var namaPropertiTidakBiasa = {
-  '': 'An empty string',
-  '!': 'Bang!'
-}
-console.log(namaPropertiTidakBiasa.'');   // SyntaxError: Unexpected string
-console.log(namaPropertiTidakBiasa['']);  // An empty string
-console.log(namaPropertiTidakBiasa.!);    // SyntaxError: Unexpected token !
-console.log(namaPropertiTidakBiasa['!']); // Bang!
- -

Peningkatan Literal Objek

- -

Di ES2015, literal objek diperluas untuk mendukung pengaturan prototipe pada konstruksi, singkatan untuk  foo: penugasan foo , definisikan metode, pembuatan panggilan super, dan komputasi nama properti dengan ekspresi. Bersamaan dengan itu, ini juga membawa literatur dan deklarasi kelas lebih dekat bersama, dan membiarkan desain berbasis objek mendapatkan keuntungan dari beberapa kemudahan yang sama.

- -
var obj = {
-    // __proto__
-    __proto__: theProtoObj,
-    // Shorthand for ‘handler: penangan’
-    handler,
-    // Metode
-    toString() {
-     // Pangilan super
-     return 'd ' + super.toString();
-    },
-    // Dikalkulasi (dinamis) nama properti
-    [ 'prop_' + (() => 42)() ]: 42
-};
- -

Tolong dicatat:

- -
var foo = {a: 'alpha', 2: 'two'};
-console.log(foo.a);    // alpha
-console.log(foo[2]);   // two
-//console.log(foo.2);  // Error: missing ) after argument list
-//console.log(foo[a]); // Error: a is not defined
-console.log(foo['a']); // alpha
-console.log(foo['2']); // two
- -

Literal RegExp

- -

Sebuah literal regex adalah pola yang dilampirkan diantara garis miring. Berikut ini adalah contoh literal regex.

- -
var re = /ab+c/;
- -

Literal string

- -

Literal string adalah nol atau lebih karakter yang dilampirkan dengan tanda kutip ganda (") atau tunggal ('). String harus dibatasi dengan tanda kutip dari jenis yang sama; Yaitu kedua tanda kutip tunggal atau kedua tanda petik ganda. Berikut ini adalah contoh literal string:

- -
'foo'
-"bar"
-'1234'
-'baris satu \n baris lainnya'
-"Kucing jhon"
- -

Anda dapat memanggil salah satu metode objek String pada nilai literal string-JavaScript secara otomatis mengubah literal string menjadi objek String sementara, memanggil metode tersebut, lalu membuang objek String sementara. Anda juga bisa menggunakan properti String.length dengan literal string:

- -
console.log("Kucing jhon".length)
-// Akan mencetak jumlah simbol dalam string termasuk spasi.
-// Dalam hal ini, 11.
- -

Di ES2015, template literal juga tersedia. Template string memberikan sintaksis gula untuk pembuatan string. Ini mirip dengan fitur interpolasi string di Perl, Python dan lainnya. Secara opsional, tag dapat ditambahkan untuk memungkinkan konstruksi string disesuaikan, menghindari serangan injeksi atau membangun struktur data tingkat tinggi dari konten string.

- -
// Literal dasar kreasi string
-`Dalam JavaScript '\n' adalah sebuah line-feed.`
-
-// String beberapa baris
-`Dalam template string JavaScript dapat berjalan di
- beberapa baris, namun string yang dikutip ganda dan tunggal
- tidak dapat dilakukan.`
-
-// Interpoasi string
-var name = 'Bob', time = 'today';
-`Hello ${name}, how are you ${time}?`
-
-// Membangun prefix permintaan HTTP digunakan untuk menafsirkan penggantian dan konstruksi
-POST`http://foo.org/bar?a=${a}&b=${b}
-     Content-Type: application/json
-     X-Credentials: ${credentials}
-     { "foo": ${foo},
-       "bar": ${bar}}`(myOnReadyStateChangeHandler);
- -

Anda harus menggunakan literal string kecuali Anda secara khusus perlu menggunakan objek String. Lihat {{jsxref("String")}}  untuk rincian tentang objek String.

- -

Menggunakan karakter khusus dalam string

- -

Selain karakter biasa, Anda juga bisa menyertakan karakter khusus dalam string, seperti yang ditunjukkan pada contoh berikut.

- -
'one line \n another line'
- -

Tabel berikut mencantumkan karakter khusus yang dapat Anda gunakan dalam string JavaScript.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Tabel: karakter khusus JavaScript
KarakterBerarti
\0Null Byte
\bbackspase
\fform feed
\nBaris baru
\rCariage return
\tTab
\vTab vertikal
\'Apostrof atau kutipan tunggal
\"Kutipan ganda
\\Karakter backslash
\XXXKarakter dengan pengkodean Latin-1 ditentukan oleh hingga tiga digit oktal XXX antara 0 dan 377. Misalnya, \251 adalah urutan oktal untuk simbol hak cipta.
\xXXKarakter dengan pengkodean Latin-1 yang ditentukan oleh dua digit heksadesimal XX antara 00 dan FF. Misalnya, \xA9 adalah urutan heksadesimal untuk simbol hak cipta.
\uXXXXKarakter Unicode ditentukan oleh empat digit heksadesimal XXXX . Misalnya, \u00A9 adalah urutan Unicode untuk simbol hak cipta. Lihat rangkaian pelolosan Unicode.
\u{XXXXX}Kode Unicode lolos. Misalnya, \u {2F804} sama dengan Unicode sederhana yang lolos \uD87E \uDC04.
- -

Karakter pelolosan

- -

Untuk karakter yang tidak tercantum dalam tabel, tanda garis miring terbalik sebelumnya diabaikan, namun penggunaan ini tidak berlaku lagi dan harus dihindari.

- -

Anda dapat memasukkan tanda petik di dalam string sebelum mendahului dengan garis miring terbalik. Ini dikenal sebagai pelolosan dari tanda petik. Sebagai contoh:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-console.log(quote);
- -

Hasil dari ini adalah:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
- -

Untuk menyertakan garis miring terbalik di dalam string, Anda harus melepaskan diri dari karakter garis miring terbalik. Misalnya, untuk menetapkan path file c:\temp ke string, gunakan yang berikut ini:

- -
var home = 'c:\\temp';
- -

Anda juga bisa meloloskan dari baris istirahat sebelumnya mendahului mereka dengan garis miring terbalik. Garis miring terbalik dan baris istirahat keduanya terlepas dari nilai string.

- -
var str = 'this string \
-is broken \
-across multiple \
-lines.'
-console.log(str);   // this string is broken across multiplelines.
- -

Meskipun JavaScript tidak memiliki sintaks "heredoc", Anda bisa mendekat dengan menambahkan pelolosan baris istirahat dan baris istirahat pada akhir setiap baris:

- -
var poem =
-'Roses are red,\n\
-Violets are blue.\n\
-Sugar is sweet,\n\
-and so is foo.'
- -

ECMAScript 2015 memperkenalkan tipe literal baru, yaitu  template literal . Hal ini memungkinkan banyak fitur baru termasuk string beberapa baris!

- -

 

- -
var poem =
-`Roses are red,
-Violets are blue.
-Sugar is sweet,
-and so is foo.`
- -

 

- -

Informasi lebih lanjut

- -

Bab ini berfokus pada sintaks dasar untuk deklarasi dan tipe. Untuk mempelajari lebih lanjut tentang konstruksi bahasa JavaScript, lihat juga bab-bab berikut dalam panduan ini:

- - - -

Pada bab berikutnya, kita akan melihat konstruksi aliran kontrol dan penanganan kesalahan.

diff --git a/files/id/web/javascript/guide/index.html b/files/id/web/javascript/guide/index.html deleted file mode 100644 index e1a506b560..0000000000 --- a/files/id/web/javascript/guide/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: Panduan JavaScript -slug: Web/JavaScript/Guide -translation_of: Web/JavaScript/Guide -original_slug: Web/JavaScript/Panduan ---- -
{{jsSidebar("JavaScript Guide")}}
- -

Pedoman javasript memberi tahu bagaimana menggunakan JavaScript dan memberikan penjelasan tentang bahasa javascript. Jika anda ingin memulai javascript atau programming secara umum, konsultasikan artikel di Area pembelajaran. Jika anda membutuhkan informasi lengkap tentang fitur silakan lihat  Referensi javaScript.

- -

Bagian

- -

Pedoman ini dibagi menjadi beberapa bagian:

- - - - - - - - - -

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git a/files/id/web/javascript/guide/introduction/index.html b/files/id/web/javascript/guide/introduction/index.html deleted file mode 100644 index bfe4c9072c..0000000000 --- a/files/id/web/javascript/guide/introduction/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Perkenalan -slug: Web/JavaScript/Guide/Introduction -tags: - - I10n:priority - - JavaScript - - Pedoman - - Pemula - - Perkenalan -translation_of: Web/JavaScript/Guide/Introduction -original_slug: Web/JavaScript/Panduan/pengenalan ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
- -

Bab ini mengenalkan dan membahas konsep yang mendasar di javascript.

- -

Apa yang perlu anda ketahui

- -

Pada pedoman ini kami anggap Anda memiliki pengetahuan dasar dari:

- - - -

Tempat untuk mencari informasi JavaScript 

- -

Dokumentasi JavaScript di MDN menyediakan materi sebagai berikut:

- - - -

Jika Anda baru mengenal JavaScript, mulailah dari area belajar dan Paduan JavaScript. Ketika Anda sudah mendapatkan pemahaman dasarnya, Anda bisa menggunakan Referensi JavaScript untuk melihat lebih detil objek dan statement.

- -

Apa itu JavaScript?

- -

JavaScript adalah bahasa scripting cross-platform yang berorientasi objek yang digunakan untuk membuat bagian interaktif dari halaman-halaman web (misal: animasi kompleks, tombol yang dapat di-klik, menu pop-up, dll). Terdapat juga versi server-side yang lebih lanjut dari JavaScript seperti Node.Js yang mana dapat memberikan Anda fungsionalitas lebih pada sebuah website (seperti kolaborasi realtime di antara beberapa komputer). Di dalam host environment (contoh, sebuah web browser), JavaScript dapat dihubungkan ke objek-objek dari environment tersebut untuk menyediakan kendali programmatis terhadapnya. 

- -

JavaScript memuat satu library standar yang memuat objek-objek, seperti Array, Date, dan Math, juga set inti dari elemen-elemen bahasa ini seperti operator, struktur kontrol, dan statement. Inti dari JavaScript dapat dikembangkan untuk kegunaan yang beragam dengan cara menambahkan  objek-objek tambahan; sebagai contoh:

- - - -

JavaScript dan Java

- -

JavaScript dan Java memang memiliki kemiripan pada beberapa hal, namun pada dasarnya saling berbeda. JavaScript menyerupai Java namum tidak memiliki static typing dan strong type checking. JavaScript mengikuti sebagian besar expresi syntax Java, konvensi penamaan serta konstruksi control-flow dasar, yang mana menjadi alasan untuk mengganti namanya dari LiveScript ke JavaScript.

- -

Berbeda dengan sistem compile-time class Java yang dibangun melalui deklarasi, Javascript mendukung sistem runtime yang berbasis pada sebagian kecil tipe data yang mewakili nilai numerik, Boolean, dan string. Javascript memiliki model objek berbasis prototipe ketimbang model objek berbasis kelas yang lebih umum. Model berbasis prototipe menyediakan inheritance dinamis; yaitu, apa yang diturunkan/diwariskan dapat berbeda pada setiap objek. Javascript juga mendukung fungsi tanpa persyaratan deklaratif khusus. Fungsi bisa berupa properti objek, yang dijalankan sebagai tipe metode yang longgar.

- -

JavaScript merupakan bahasa dengan bentuk yang sangat bebas dibandingkan dengan Java. Anda tidak perlu mendeklarasikan semua variabel, kelas, dan metode. Anda tidak perlu khawatir apakah metode itu public, private, atau protected, dan Anda juga tidak perlu mengimplementasikan interface. Variabel, parameter, dan tipe kembalian fungsi juga tidak ditulis secara eksplisit.

- -

Java merupakan bahasa berbasis kelas yang didesain untuk eksekusi yang cepat dan penulisan yang aman. Penulisan yang aman, misalnya, Anda tidak bisa mengubah integer Java menjadi referensi objek atau mengakses private memori dengan membobol bytecode. Model berbasis kelas Java bermaksud bahwa program secara eksklusif terdiri atas sejumlah kelas beserta metode-metodenya. Pewarisan kelas dan penulisan ketat milik Java umumnya membutuhkan hirarki objek yang juga sangat kekat. Syarat-syarat tersebut menjadikan pemrograman Java lebih kompleks ketimbang pemrograman Javascript.

- -

Sebaliknya, JavaScript mewarisi inti dari baris bahasa yang bertipe dinamis dan lebih sederhana sepeti HyperTalk dan dBASE. Bahasa-bahasa scripting tersebut menawarkan fungsionalitas pemrograman ke pengguna yang lebih luas karena syntax-nya yang lebih mudah, berfokus pada fungsi built-in, dan persyaratan yang minimalis untuk membuat objek.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript dibandingkan Java
JavaScriptJava
Berorientasi objek. Tak ada perbedaan antar tipe objek. Inheritance/ pewarisan melalui mekanisme prototipe, serta properti dan metode bisa ditambahkan kepada objek apapun secara dinamis.Berbasis kelas. Objek dibagi ke dalam kelas dan instansi dengan semua pewarisan melalui hirarki kelas. Kelas dan instansi tidak dapat memiliki properti atau metode yang ditambahkan secara dinamis.
Tipe data variabel tidak dideklarasi (dynamic typing, loosely typed).Tipe data variabel harus dideklarasi (static-typing, strongly typed).
Tidak bisa menulis ke hard disk secara otomatis.Bisa menulis ke hard disk secara otomatis.
- -

Untuk informasi lebih lanjut perbedaan antara JavaScript dan Java, lihat bagian Detil dari model objek.

- -

JavaScript dan spesifikasi ECMAScript

- -

Javascript distandarisasi melalui Ecma International — asosiasi Eropa yang men-standarisasi sistem informasi dan komunikasi  (ECMA merupakan singkatan yang dari European Computer Manufacturers Association) yang mengurusi standarisasi bahasa pemrograman internasional berbasis JavaScript. Versi standarisasi JavaScript ini, yang disebut sebagai ECMAScript, akan berperilaku sama pada setiap aplikasi yang mengikutinya. Perusahaan-perusahaan dapat menggunakan bahasa standar terbuka untuk mengembangkan implementasi JavaScript mereka. Standar ECMAScript didokumentasikan dalam spesifikasi ECMA-262. Kunjungi Terbaru di JavaScript untuk mempelajari lebih lanjut tentang berbagai versi dari JavaScript dan spesifikasi edisi ECMAScript.

- -

Standar ECMA-262 juga disetujui oleh ISO (International Organization for Standardization) sebagai ISO-16262. Anda juga dapat menemukan spesifikasinya di website Ecma International. Spesifikasi ECMAScript tidak memaparkan Document Object Model yang distandarisasi oleh World Wide Web Consortium (W3C) bersama WHATWG (Web Hypertext Application Technology Working Group). DOM mendefinisikan cara dimana dokumen objek HTML diekspos ke script Anda. Untuk mendapatkan pemahaman yang lebih baik tentang berbagai teknologi yang digunakan ketika memrogram menggunakan JavaScript, lihat artikel ikhtisar teknologi JavaScript.

- -

Perbandingan dokumentasi JavaScript dengan spesifikasi ECMAScript

- -

Spesifikasi ECMAScript adalah seperangkat persyaratan untuk menerapkan ECMAScript; berguna jika Anda ingin menerapkan fitur bahasa yang sesuai standar dalam penerapan atau mesin ECMAScript Anda (seperti SpiderMonkey di Firefox, atau V8 di Chrome).

- -

Dokumen ECMAScript tidak dimaksudkan untuk membantu script programmer; gunakanlah dokumentasi JavaScript untuk informasi dalam penulisan script.

- -

Spesifikasi ECMAScript menggunakan terminologi dan syntax yang mungkin asing bagi programmer JavaScript. Meskpun deskripsi dari bahasa tersebut dapat berbeda dengan ECMAScript, bahasanya sendiri tetap sama. JavaScript mendukung semua fungsionalitas yang diuraikan dalam spesifikasi ECMAScript.

- -

Dokumentasi JavaScript menggambarkan aspek bahasa yang sesuai bagi seorang programmer JavaScript.

- -

Memulai Javascript

- -

Memulai JavaScript itu mudah: semua yang dibutuhkan hanyalah Web browser modern untuk menjalankannya. Panduan ini mencakup beberapa fitur JavaScript yang hanya tersedia pada versi terakhir Firefox, sehingga disarankan untuk menggunakan Firefox versi terbaru.

- -

Terdapat dua alat yang dipasang ke dalam Firefox yang berguna dalam bereksperimen dengan JavaScript: Web Console dan Scratchpad.

- -

Web Console

- -

Web Consol / Konsol Web memperlihatkan kepada Anda tentang informasi laman Web yang sedang di-load saat ini, dan juga mencakup commandline / baris perintah yang dapat Anda gunakan untuk mengeksekusi ekspresi JavaScript pada laman saat ini.

- -

Untuk membuka Konsol Web, tekan (Ctrl + Shift + K) pada Windows dan Linux atau tekan (Cmd + Option + K) pada Mac, pilih "Web Console" dari menu "Developer", yang berada di bawah menu "Tools" di Firefox. Konsol akan muncul di bagian bawah jendela browser. Di bagian bawah konsol tersebut adalah command line yang dapat Anda gunakan untuk memasukkan JavaScript, dan outputnya akan muncul pada panel di atasnya.

- -

Konsol tersebut bekerja persis seperti eval: expresi terakhir yang dienter akan dikembalikan. Demi kesederhanaan, bisa dibayangkan jika setiap saat sesuatu dimasukkan ke dalam konsol, ia akan selalu dikelilingi oleh console.log sekitar eval seperti ini.

- -
function greetMe(yourName) {
-  alert('Hello ' + yourName);
-}
-console.log(eval('3 + 5'));
- -

 

- -

Scratchpad

- -

Konsol Web bagus untuk menjalankan satu baris kode JavaScript, meskipun Anda juga dapat menjalankan banyak baris, tetap saja akan terasa kurang nyaman, dan Anda juga tidak bisa menyimpan sampel kode Anda menggunakan Konsol Web. Jadi untuk contoh yang lebih kompleks, Scratchpad adalah solusinya.

- -

Untuk membuka Scratchpad tekan (Shift + F4), pilih "Scratchpad" dari menu "Developer", yang ada di bawah menu pada Firefox. Selanjutnya akan muncul di window yang terpisah dan merupakan editor yang dapat Anda gunakan untuk menulis dan menjalankan JavaScript di browser. Anda juga dapat menyimpan dan membuka kode dari disk.

- -

- -

Hello world

- -

Untuk mulai menulis JavaScript, buka Scratchpad dan tulislah kode JavaScript "Hello world" pertama Anda:

- -
(function(){
-  "use strict";
-  /* Start of your code */
-  function greetMe(yourName) {
-    alert('Hello ' + yourName);
-  }
-
-  greetMe('World');
-  /* End of your code */
-})();
-
- -

Pilih kode diatas dan tekan Ctrl+R untuk melihatnya berjalan di browser Anda! Di laman-laman berikutnya, panduan ini akan memperkenalkan Anda dengan syntax dan fitur-fitur bahasa JavaScript, sehingga Anda dapat menulis aplikasi yang lebih kompleks. Tapi untuk saat ini, ingatlah untuk selalu memasukkan (function(){"use strict"; sebelum kode Anda, dan tambahkan  })(); di akhir kode Anda. Anda akan mempelajari apa artinya itu, tetapi untuk sekarang mereka bisa dianggap melakukan:

- -
    -
  1. Meningkatkan performa secara masif
  2. -
  3. Mencegah semantik ceroboh dalam JavaScript yang menjatuhkan pemula
  4. -
  5. Mencegah code snippets yang dieksekusi dalam konsol untuk berinteraksi satu sama lain (misalnya sesuatu yang dibuat dalam suatu eksekusi konsol digunakan untuk eksekusi konsol yang lain).
  6. -
- -

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

diff --git a/files/id/web/javascript/guide/loops_and_iteration/index.html b/files/id/web/javascript/guide/loops_and_iteration/index.html deleted file mode 100644 index 506b033350..0000000000 --- a/files/id/web/javascript/guide/loops_and_iteration/index.html +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Loops and iteration -slug: Web/JavaScript/Guide/Loops_and_iteration -translation_of: Web/JavaScript/Guide/Loops_and_iteration -original_slug: Web/JavaScript/Panduan/Loops_and_iteration ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}
- -

Loop menawarkan cara cepat dan mudah untuk melakukan sesuatu secara berulang-ulang. Bab tentang Panduan JavaScript ini memperkenalkan berbagai pernyataan iterasi berbeda yang tersedia untuk JavaScript.

- -

Anda dapat menganggap loop sebagai versi permainan terkomputerisasi di mana Anda menyuruh seseorang untuk mengambil langkah X menuju satu arah lalu langkah Y ke arah yang lain; Sebagai contoh, gagasan "Pergilah lima langkah ke timur" dapat di ekspresikan dengan cara berikut sebagai sebuah loop (pengulangan):

- -
var langkah;
-for (langkah= 0; langkah< 5; langkah++) {
-  // berlari 5 kali, dengan nilai langkah 0 sampai 4.
-  console.log('Berjalan ke timur satu langkah');
-}
-
- -

Ada beberapa jenis loop yang berbeda, namun pada dasarnya semuanya melakukan hal yang sama, mereka mengulangi sebuah aksi beberapa kali (dan sebenarnya memungkinkan bahwa dapat saja menjadi nol). Berbagai mekanisme loop menawarkan berbagai cara untuk menentukan titik awal dan akhir perulangan. Ada berbagai situasi yang lebih mudah dikerjakan oleh sebuah tipe loop dibandingkan tipe (loop) yang lain.

- -

Pernyataan untuk loop yang disediakan dalam JavaScript adalah:

- - - -

for statement

- -

Sebuah {{jsxref("statements/for","for loop")}} mengulang hingga kondisi yang ditentukan evaluasinya menjadi salah/false.  for loop pada Javascript serupa dengan  for loop pada Java dan C. Sebuah statement (pernyataan) for   terlihat sebagai berikut:

- -
for ([initialExpression]; [condition];
-[incrementExpression]) statement
-
- -

Ketika sebuah for loop dieksekusi, Berikut ini akan terjadi:

- -
    -
  1. Ekspresi yang menginisialisasi yaitu initialExpression, Jika ada, maka akan di eksekusi. Ekspresi ini biasanya menginisialisasi satu atau lebih penghitung loop, tetapi sintaksnya memperbolehkan ekspresi dengan tingkat kerumitan apapun. Ekspresi ini juga bisa mendeklarasikan variabel.
  2. -
  3. Ekpresi condition di evaluasi. JIka value dari kondisi adalah true (benar), maka statement loop akan dieksekusi. Jika value dari condition false (salah), for loop akan dihentikan.  Jika ekspresi condition dihilangkan sama sekali, kondisinya diasumsikan benar.
  4. -
  5. Mengeksekusi Statement . Untuk mengeksekusi berbagai pernyataan, gunakanlah sebuah blok pernyataan ({ ... }untuk mengelompokkan pernyataan-pernyataan tersebut.
  6. -
  7. Jika ada, ekspresi baru incrementExpression di eksekusi.
  8. -
  9. Kontrol kembali ke langkah ke-2.
  10. -
- -

Contoh

- -

function (fungsi) berikut memuat sebuah statement for yang menghitung angka dari opsi yang terpilih dalam sebuah daftar scrolling  (sebuah elemen {{HTMLElement("select")}} yang memperbolehkan berbagai pilihan). Statement for mendeklarasikan variable i dan menginisialisasinya ke nol. Ia memeriksa bahwa i lebih kecil dari nomor dari opsi dalam elemen <select> , menampilkan statement if yang berhasil, dan menaikan i satu setelah masing-masing lolos melewati loop.

- -
<form name="selectForm">
-  <p>
-    <label for="musicTypes">Choose some music types, then click the button below:</label>
-    <select id="musicTypes" name="musicTypes" multiple="multiple">
-      <option selected="selected">R&B</option>
-      <option>Jazz</option>
-      <option>Blues</option>
-      <option>New Age</option>
-      <option>Classical</option>
-      <option>Opera</option>
-    </select>
-  </p>
-  <p><input id="btn" type="button" value="How many are selected?" /></p>
-</form>
-
-<script>
-function howMany(selectObject) {
-  var numberSelected = 0;
-  for (var i = 0; i < selectObject.options.length; i++) {
-    if (selectObject.options[i].selected) {
-      numberSelected++;
-    }
-  }
-  return numberSelected;
-}
-
-var btn = document.getElementById('btn');
-btn.addEventListener('click', function() {
-  alert('Number of options selected: ' + howMany(document.selectForm.musicTypes));
-});
-</script>
-
-
- -

do...while statement

- -

Pernyataan/statement {{jsxref("statements/do...while", "do...while")}} terus di ulangi sampai evaluasi kondisi bernilai false/salah. Sebuah do...while statement terlihat sebagai berikut:

- -
do
-  statement
-while (condition);
-
- -

statement di jalankan lebih dulu sebelum kondisi diperiksa. Untuk menjalankan banyak statements, gunakan statement blok ({ ... }) untuk membuat grup dari statement tersebut. Jika condition bernilai benar, maka statement akan dijalankan kembali. Kondisi diperiksa pada setiap akhir eksekusi. Ketika kondisi bernilai salah, eksekusi berhenti dan kontrol akan melewati pernyataan yang mengikuti do...while.

- -

Contoh

- -

Dalam contoh berikut, perulangan do di iterasi sekali dan di iterasi kembali sampai i tidak lagi kurang dari 5. 

- -
var i = 0;
-do {
-  i += 1;
-  console.log(i);
-} while (i < 5);
- -

while statement

- -

Sebuah statement {{jsxref("statements/while","while")}} di eksekusi pernyataan pernyataannya asalkan memenuhi syarat kondisinya yang bernilai true/benar. Sebuah statement  while terlihat sebagai berikut:

- -
while (condition)
-  statement
-
- -

Jika kondisi bernilai false/salah, statement dengan perulangan berhenti di eksekusi dan kontrol akan melewati statement yang mengikuti perulangan tersebut.

- -

Kondisi terjadi sebelum statement dalam perulangan di eksekusi. Jika kondisi bernilai true/benar, statement di eksekusi dan kondisi di uji kembali. Jika kondisi bernilai false/salah, eksekusi akan berhenti dan konrol lewat untuk statement yang mengikuti while.

- -

Untuk mengeksekusi banyak statement, gunakan blok statement ({ ... }) untuk mengelompokan banyak statement tersebut.

- -

Contoh 1

- -

Beikut perulangan while mengiterasi n selama n kurang dari tiga:

- -
var n = 0;
-var x = 0;
-while (n < 3) {
-  n++;
-  x += n;
-}
-
- -

Dengan setiap iterasi, perulangan akan menambahkan increments n dan menambahkan nilainya pada  x. Karena itu, x dan n mengambil nilai nilai berikut:

- - - -

Setelah melewati perulangan yang ketiga , kondisinya n < 3 tidak lagi bernilai true/benar, jadi perulangan di hentikan.

- -

Contoh 2

- -

Hindari perulangan tanpa batas. Pastikan kondisi dalam perulangan mendapatkan kondisi yang bernilai false/salah untuk berhenti, jika tidak perulangan tidak akan pernah berhenti. Statements dalam while berikut di eksekusi berulang kali selamanya karena kondisi tidak pernah mendapatkan nilai false/salah:

- -
while (true) {
-  console.log('Hello, world!');
-}
- -

labeled statement

- -

Sebuah {{jsxref("statements/label","label")}} menyediakan sebuah statement dengan pengenal yang memungkinkan Anda merujuknya di tempat lain dalam program Kamu. Untuk contohnya, Kamu dapat menggunakan label untuk mengidentifikasi pengulangan, lalu gunakan statement break atau continue untuk menunjukkan apakah suatu program harus memutuskan loop atau melanjutkan eksekusinya.

- -

Sintak dari statement berlabel terlihat seperti berikut:

- -
label :
-   statement
-
- -

Nilai dai sebuah label dapat berupa identifikasi JavaScript apa pun yang tidak dari kata  kunci yang ada pada javascript. statement
- yang Kamu identifikasi dengan label tersebut dapat berupa statement apa pun.

- -

Contoh

- -

Pada contoh ini, label markLoop mengidentifikasi sebuah perulangan while.

- -
markLoop:
-while (theMark == true) {
-   doSomething();
-}
- -

break statement

- -

Gunakan {{jsxref("statements/break","break")}} statement untuk menghentikan perulangan, switch, atau konjungsi dengan statement yang memakai label.

- - - -

Sintak dari statement break terlihat seperti ini:

- -
break [label];
-
- -

Bentuk pertama sintak mengakhiri perulangan atau switch; Bentuk kedua sintak mengakhiri statement dari spesifik label.

- -

Contoh 1

- -

Contoh berikut mengiterasi melewati elemen-elemen dalam array sampai menemukan indeks elemen  yang bernilai dari theValue:

- -
for (var i = 0; i < a.length; i++) {
-  if (a[i] == theValue) {
-    break;
-  }
-}
- -

Contoh 2: Breaking pada sebuah label

- -
var x = 0;
-var z = 0;
-labelCancelLoops: while (true) {
-  console.log('Outer loops: ' + x);
-  x += 1;
-  z = 1;
-  while (true) {
-    console.log('Inner loops: ' + z);
-    z += 1;
-    if (z === 10 && x === 10) {
-      break labelCancelLoops;
-    } else if (z === 10) {
-      break;
-    }
-  }
-}
-
- -

continue statement

- -

Statement {{jsxref("statements/continue","continue")}} bisa digunakan untuk memulai lagi statement while, do-while, for, atau label.

- - - -

Sintak statement continue terlihat sebagai berikut:

- -
continue [label];
-
- -

Contoh 1

- -

Contoh berikut menunjukkan sebuah perulangan while dengan sebuah statement continue yang di eksekusi ketika niai dari i adalah tiga  Jadi, n mengambil nilai satu, tiga, tujuh dan dua belas.

- -
var i = 0;
-var n = 0;
-while (i < 5) {
-  i++;
-  if (i == 3) {
-    continue;
-  }
-  n += i;
-}
-
- -

Contoh 2

- -

Sebuah statement yang berlabel checkiandj berisikan sebuah statement berlabel checkj. Jika ada continue , Programnya akan menghentikan iterasi saat ini dari checkj dan memulai iterasi selanjutnya. Setiap kali continue ditemui, checkj  di iterasi kembali sampai kondisinya bernilai false/salah. Ketika bernilai false/salah, Sisa dari statement checkiandj sudah selesai, dan checkiandj di iterasi kembali sampai kondisi bernilai salah false. Ketika bernilai salah false , program melanjutkan pada statement yang mengikuti checkiandj.

- -

JIka continue dipunyai label dari checkiandj, program akan terus berlanjut ke bagian atas dari statement checkiandj .

- -
checkiandj:
-  while (i < 4) {
-    console.log(i);
-    i += 1;
-    checkj:
-      while (j > 4) {
-        console.log(j);
-        j -= 1;
-        if ((j % 2) == 0) {
-          continue checkj;
-        }
-        console.log(j + ' is odd.');
-      }
-      console.log('i = ' + i);
-      console.log('j = ' + j);
-  }
- -

for...in statement

- -

Statement {{jsxref("statements/for...in","for...in")}} mengiterasi sebuah variabel spesifik diatas properti enumerable dari sebuah objek. Untuk setiap properti yang berbeda, JavaScript mengeksekusi pernyataan pernyataan yang spesifik. Sebuah statement for...in terlihat sebagai berikut:

- -
for (variable in object) {
-  statements
-}
-
- -

Contoh

- -

Function/fungsi berikut mengambil argumentnya dari sebuah objek dan nama objek. Lalu dia di iterasi diatas semua property objek dan mengembalikan sebuah string yang mendaftarkan nama properti dan nilainya.

- -
function dump_props(obj, obj_name) {
-  var result = '';
-  for (var i in obj) {
-    result += obj_name + '.' + i + ' = ' + obj[i] + '<br>';
-  }
-  result += '<hr>';
-  return result;
-}
-
- -

Untuk sebuah objek car dengan property make dan model, result/hasil akan menjadi:

- -
car.make = Ford
-car.model = Mustang
-
- -

Arrays

- -

Meskipun mungkin menggunakan ini sebagai cara untuk melakukan iterasi di atas elemen {{jsxref("Array")}},statement for...in akan mengembalikan nilai nama property yang di tetapkan pengguna dalam penambahan numerik indek. Jadi lebih baik menggunakan tradisional perulangan {{jsxref("statements/for","for")}} dengan sebuah numerik indek ketika mengiterasi diatas array, karena statement  for...in mengiterasi diatas nama properti yang di tetapkan pengguna pada penambahan elemen array, Jika kamu merubah array, seperti menambahkan properti atau metode. 

- -

for...of statement

- -

Statement {{jsxref("statements/for...of","for...of")}} membuat sebuah iterasi perulangan diatas iterable objects (termasuk {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("functions/arguments","arguments")}} object dan seterusnya), menjalankan hubungan iterasi khusus dengan statement yang akan dieksekusi untuk setiap nilai properti yang berbeda.

- -
for (variable of object) {
-  statement
-}
- -

Contoh berikut menampilkan perbedaan diantara sebuah perulangan for...of dan sebuah perulangan {{jsxref("statements/for...in","for...in")}}. Ketika for...in mengiterasi diatas nama-nama properti, for...of mengiterasi diatas nilai-nilai properti:

- -
let arr = [3, 5, 7];
-arr.foo = 'hello';
-
-for (let i in arr) {
-   console.log(i); // logs "0", "1", "2", "foo"
-}
-
-for (let i of arr) {
-   console.log(i); // logs 3, 5, 7
-}
-
- -

{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}

diff --git a/files/id/web/javascript/guide/numbers_and_dates/index.html b/files/id/web/javascript/guide/numbers_and_dates/index.html deleted file mode 100644 index 81ff248515..0000000000 --- a/files/id/web/javascript/guide/numbers_and_dates/index.html +++ /dev/null @@ -1,377 +0,0 @@ ---- -title: Numbers and dates -slug: Web/JavaScript/Guide/Numbers_and_dates -translation_of: Web/JavaScript/Guide/Numbers_and_dates -original_slug: Web/JavaScript/Panduan/Numbers_and_dates ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}
- -

Pada Bab ini memperkenalkan cara menggunakan angka dan tanggal pada JavaScript.

- -

Angka

- -

Pada JavaScript, semua angka diimplementasikan kedalam double-precision 64-bit binary format IEEE 754 (mis. angka antara -(253 -1) dan 253 -1). Tidak ada jenis spesifik untuk integer. Selain bisa mewakili angka float, tipe data angka memiliki 3 nilai secara simbolik: +{{jsxref("Infinity")}}, -{{jsxref("Infinity")}}, dan {{jsxref("NaN")}} (bukan sebuah angka). Lihat juga JavaScript tipe data dan struktur untuk konteks dengan tipe data primitif JavaScript yang lain.

- -

Anda dapat menggunakan empat tipe angka literal: desimal, biner, oktal, dan heksadesimal.

- -

Angka Desimal

- -
1234567890
-42
-
-// Perhatikan ketika menggunakan angka berawalan nol:
-
-0888 // 888 diubah menjadi desimal
-0777 // diubah menjadi oktal pada non-strict mode (511 in decimal)
-
- -

Perhatikan bahwa desimal literal dapat dimulai dari nol(0) diikuti angka desimal yang lain, namun jika setiap angka setelah 0 lebih kecil dari 8, angkanya diubah menjadi oktal.

- -

Angka Biner

- -

Sintaks angka biner menggunakan angka nol diikuti dengan huruf kecil atau dengan huruf besar, huruf Latin "B" (0b atau 0B). Jika digit setelah 0b atau bukan 0 atau 1, menurut SyntaxError yang dilemparkan: "Missing binary digits after 0b".

- -
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
-var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
-var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
- -

Angka oktal

- -

Angka oktal menggunakan awalan angka nol. Jika digit setelah 0 berada diluar jangkauan 0 hinga 7, angka akan diintrepretasikan sebagai angka desimal.

- -
var n = 0755; // 493
-var m = 0644; // 420
-
- -

Mode ketat pada ECMAScript 5 melarang sintaks oktal. Oktal sintaks bukan bagian dari ECMAScript 5, namun didukung oleh semua peramban dengan cara awalan nomor oktal dengan angka nol: 0644 === 420 dan "\045" === "%". Pada ECMAScript 2015, angka oktal didukung jika diawali dengan 0o, e.g.: 

- -
var a = 0o10; // ES2015: 8
-
- -

Angka Heksadesimal

- -

Sintaks heksadesimal menggunakan awalan nol diikuti dengan huruf kecil atau huruf kapital Latin "X" (0x atau 0X). Jika digit setelah 0x berada diluar jangkauan (0123456789ABCDEF),  menurut SyntaxError yang dilemparkan: "Identifier starts immediately after numeric literal".

- -
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
-0x123456789ABCDEF   // 81985529216486900
-0XA                 // 10
-
- -

Eksponensial

- -
1E3   // 1000
-2e6   // 2000000
-0.1e2 // 10
- -

Angka object

- -

The built-in {{jsxref("Number")}} objek memiliki properti untuk numerik konstanta, seperti nilai maksimal, bukan-sebuah-angka, dan tak terhingga. Anda tidak dapat mengganti nilai dari properti tersebut dan anda dapat menggunakannya sebagai berikut:

- -
var biggestNum = Number.MAX_VALUE;
-var smallestNum = Number.MIN_VALUE;
-var infiniteNum = Number.POSITIVE_INFINITY;
-var negInfiniteNum = Number.NEGATIVE_INFINITY;
-var notANum = Number.NaN;
-
- -

Anda selalu mengacu pada properti dari objek angka yang telah ditentukan seperti yang ditunjukkan diatas, dan bukan sebagai properti objek angka yang anda tentukan.

- -

Tabel berikut meringkas sifat-sifat nomor object.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Properties of Number
PropertiDeskripsi
{{jsxref("Number.MAX_VALUE")}}Merepresantikan angka maksimal / terbesar
{{jsxref("Number.MIN_VALUE")}}Merepresantikan angka minimal / terkecil
{{jsxref("Number.NaN")}}Nilai spesial "bukan sebuah angka"
{{jsxref("Number.NEGATIVE_INFINITY")}}Nilai spesial negatif tak terhingga; dikembalikan pada overflow
{{jsxref("Number.POSITIVE_INFINITY")}}Nilai spesial positif tak terhingga; dikembalikan pada overflow
{{jsxref("Number.EPSILON")}}Perbedaan antara satu dan nilai terkecil lebih besar dari satu yang dapat direpresentasikan sebagai {{jsxref("Number")}}.
{{jsxref("Number.MIN_SAFE_INTEGER")}}Bilangan bulat aman minimum dalam JavaScript.
{{jsxref("Number.MAX_SAFE_INTEGER")}}Bilangan bulat aman maksimum dalam JavaScript.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Methods of Number
MethodDescription
{{jsxref("Number.parseFloat()")}}Parses a string argument and returns a floating point number.
- Same as the global {{jsxref("parseFloat", "parseFloat()")}} function.
{{jsxref("Number.parseInt()")}}Parses a string argument and returns an integer of the specified radix or base.
- Same as the global {{jsxref("parseInt", "parseInt()")}} function.
{{jsxref("Number.isFinite()")}}Determines whether the passed value is a finite number.
{{jsxref("Number.isInteger()")}}Determines whether the passed value is an integer.
{{jsxref("Number.isNaN()")}}Determines whether the passed value is {{jsxref("Global_Objects/NaN", "NaN")}}. More robust version of the original global {{jsxref("Global_Objects/isNaN", "isNaN()")}}.
{{jsxref("Number.isSafeInteger()")}}Determines whether the provided value is a number that is a safe integer.
- -

Prototipe Angka menyediakan metode-metode untuk menampilkan informasi dari objek angka dalam format bervariasi. Tabel berikut meringkas metode-metode prototipe angka.

- - - - - - - - - - - - - - - - - - - - - - - -
Methods of Number.prototype
MethodDescription
{{jsxref("Number.toExponential", "toExponential()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi eksponensial.
{{jsxref("Number.toFixed", "toFixed()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi fixed-point.
{{jsxref("Number.toPrecision", "toPrecision()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi fixed-point yang lebih spesifik.
- -

Math object

- -

The built-in {{jsxref("Math")}} objek memiliki properti dan metode-metode untuk konstanta matematika dan fungsi-fungsi. Sebagai contoh, objek matematik PI properti memiliki nilai (3.141...), yang akan anda gunakan dalam aplikasi sebagai

- -
Math.PI
-
- -

Demikian pula, fungsi standard matematika merupakan metode-metode Math. termasuk trigonometri, logaritma, eksponensial, dan fungsi lainnya. Sebagai contoh, jika anda ingin menggunakan fungsi trigonometri sin, anda akan menulis

- -
Math.sin(1.56)
-
- -

Perhatikan bahwa semua metode trigonometri matematika menggunakan argumen dalam radian.

- -

Tabel berikut meringkas metode-metode objek matematik.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Methods of Math
MethodDescription
{{jsxref("Math.abs", "abs()")}}Nilai absolut
{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}Fungsi trigonometri standar; dengan argumen dalam radian.
{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}Fungsi trigonometri terbalik; mengembalikan nilai dalam radian.
{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}Fungsi hiperbolik. argumen dalam sudut hiperbolik.
{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}Fungsi hiperbolik terbalik. mengembalikan nilai dalam sudut hiperbolik.
-

{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}, {{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}

-
Fungsi eksponen dan logaritma.
{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}}Mengembalikan angka bulat terkecil/terbesar kurang/lebih dari atau sama dengan pada sebuah argumen.
{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}Mengembalikan nilai minimum/maksimum sebuah koma terpisah dari angka sebagai argumen.
{{jsxref("Math.random", "random()")}}Megembalikan angka acak antara 0 dan 1.
{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},Fungsi pembulatan dan pemotongan.
{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}}Akar kuadrat, akar pangkat tiga, akar kuadrat dari jumlah argumen persegi.
{{jsxref("Math.sign", "sign()")}}tanda sebuah angka, mengindikasikan angka apapun merupakan angka positif, negatif, atau nol.
{{jsxref("Math.clz32", "clz32()")}},
- {{jsxref("Math.imul", "imul()")}}
Angka yang dimulai dari nol bit dalam 32-bit.
- Hasil dari C-like 32-bit perkalian dari dua argumen.
- -

Tidak seperti beberapa objek lainnya, anda tidak perlu membuat objek matematika sendiri. anda selalu menggunakan built-in Math object.

- -

Date object

- -

JavaScript does not have a date data type. However, you can use the {{jsxref("Date")}} object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.

- -

JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00, with a Unix Timestamp being the number of seconds since January 1, 1970, 00:00:00.

- -

The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.

- -

To create a Date object:

- -
var dateObjectName = new Date([parameters]);
-
- -

where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.

- -

Calling Date without the new keyword returns a string representing the current date and time.

- -

The parameters in the preceding syntax can be any of the following:

- - - -

Methods of the Date object

- -

The Date object methods for handling dates and times fall into these broad categories:

- - - -

With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:

- - - -

For example, suppose you define the following date:

- -
var Xmas95 = new Date('December 25, 1995');
-
- -

Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 1995.

- -

The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date object.

- -

For example, the following code displays the number of days left in the current year:

- -
var today = new Date();
-var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
-endYear.setFullYear(today.getFullYear()); // Set year to this year
-var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
-var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
-var daysLeft = Math.round(daysLeft); //returns days left in the year
-
- -

This example creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days.

- -

The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object:

- -
var IPOdate = new Date();
-IPOdate.setTime(Date.parse('Aug 9, 1995'));
-
- -

Example

- -

In the following example, the function JSClock() returns the time in the format of a digital clock.

- -
function JSClock() {
-  var time = new Date();
-  var hour = time.getHours();
-  var minute = time.getMinutes();
-  var second = time.getSeconds();
-  var temp = '' + ((hour > 12) ? hour - 12 : hour);
-  if (hour == 0)
-    temp = '12';
-  temp += ((minute < 10) ? ':0' : ':') + minute;
-  temp += ((second < 10) ? ':0' : ':') + second;
-  temp += (hour >= 12) ? ' P.M.' : ' A.M.';
-  return temp;
-}
-
- -

The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute, and second to hour, minute, and second.

- -

The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour - 12), otherwise simply hour, unless hour is 0, in which case it becomes 12.

- -

The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way.

- -

Finally, a conditional expression appends "P.M." to temp if hour is 12 or greater; otherwise, it appends "A.M." to temp.

- -

{{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}

diff --git a/files/id/web/javascript/guide/working_with_objects/index.html b/files/id/web/javascript/guide/working_with_objects/index.html deleted file mode 100644 index 4baf443489..0000000000 --- a/files/id/web/javascript/guide/working_with_objects/index.html +++ /dev/null @@ -1,493 +0,0 @@ ---- -title: Bekerja dengan objek -slug: Web/JavaScript/Guide/Working_with_Objects -tags: - - I10n:priority - - JavaScript - - Konstruktor - - Membandingkan objek - - Objek - - Panduan - - Pemula - - dokumen -translation_of: Web/JavaScript/Guide/Working_with_Objects -original_slug: Web/JavaScript/Panduan/Working_with_Objects ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
- -

JavaScript dirancang berdasarkan paradigma berbasis objek sederhana. Objek adalah kumpulan dari properti, dan properti adalah sepasang hubungan antara nama (atau kunci) dan nilai. Nilai properti bisa berupa fungsi, Dalam hal ini properti itu disebut metode. Selain objek yang sudah di tentukan pada peramban, Kamu bisa menentukan objekmu sendiri. Bab ini menjelaskan cara memakai objek, properti, fungsi, dan metode, serta bagaimana cara membuat objekmu sendiri.

- -

Ikhtisar objek

- -

Objek di JavaScript sama seperti kebanyakan bahasa pemrograman lainnya, bisa dibandingkan dengan objek dalam kehidupan nyata. Konsep objek dalam JavaScript dapat dipahami dengan kehidupan nyata, objek nyata.

- -

Di JavaScript, objek adalah entitas yang mandiri dengan properti dan tipe. Bandingkan dengan cangkir, misalnya. Sebuah cangkir adalah objek dengan banyak properti. Cangkir punya warna, desain, berat, materi bahan, dll. Dengan cara sama, objek JavaScript juga punya banyak properti yang menjelaskan karakteristiknya.

- -

Objek dan properti

- -

Objek JavaScript punya banyak properti yang terkait dengannya. Properti dari objek dapat didefinisikan sebagai variabel yang dilampirkan pada objek itu. Properti dari objek pada dasarnya sama dengan variabel JavaScript biasa, kecuali lampiran pada objek. Properti objek menentukan karakteristik objek itu. Kamu mengakses properti objek dengan sebuah notasi titik sederhana:

- -
objectName.propertyName
-
- -

Seperti semua variabel JavaScript, baik nama objek (bisa jadi variabel normal) maupun nama properti peka terhadap besar huruf. Kamu bisa mendefinisi properti dengan mengassign nilai. Contohnya, ayo buat objek bernama myCar dan dan berikan dia properti bernama make, model, dan year sebagai berikut:

- -
var myCar = new Object();
-myCar.make = 'Ford';
-myCar.model = 'Mustang';
-myCar.year = 1969;
-
- -

Nilai properti objek yang tidak diassign adalah {{jsxref("undefined")}} (dan bukan {{jsxref("null")}}).

- -
myCar.color; // undefined
- -

Properti dari objek JavaScript juga bisa diakses atau diset menggunakan notasi kurung siku (untuk lebih detil lihat aksesor properti). Terkadang objek disebut associative array, karena tiap properti dikaitkan dengan nilai string yang bisa digunakan untuk mengaksesnya. Jadi, contohnya, kamu bisa mengakses properti dari objek myCar seperti berikut:

- -
myCar['make'] = 'Ford';
-myCar['model'] = 'Mustang';
-myCar['year'] = 1969;
-
- -

Nama properti objek bisa berupa string dari JavaScript yang valid, atau apapun yang dapat diubah menjadi string, termasuk string kosong. Namun, nama properti apapun yang tidak valid sebagai identitas di JavaScript (contohnya, nama properti yang memiliki spasi atau tanda hubung, atau yang dimulai dengan angka) hanya bisa diakses menggunakan notasi kurung siku. Notasi ini juga sangat berguna ketika nama properti harus ditentukan secara dinamis (ketika nama properti belum ditentukan hingga runtime). Contohnya sebagai berikut:

- -
// empat variabel dibuat dan diberi nilai sekali jalan,
-// dipisahkan oleh koma
-var myObj = new Object(),
-    str = 'myString',
-    rand = Math.random(),
-    obj = new Object();
-
-myObj.type              = 'Syntax titik';
-myObj['date created']   = 'String dengan spasi';
-myObj[str]              = 'Nilai string';
-myObj[rand]             = 'Angka Random';
-myObj[obj]              = 'Objek';
-myObj['']               = 'Bahkan string kosong';
-
-console.log(myObj);
-
- -

Tolong dicatat bahwa semua kunci di dalam notasi kurung siku diubah ke dalam tipe String, karena objek JavaScript hanya bisa punya tipe String sebagai tipe kunci. Contohnya, dalam kode di atas, ketika kunci  obj ditambahkan dalam myObj, JavaScript akan memanggil method obj.toString() , dan menggunakan hasil string ini sebagai kunci baru.

- -

Kamu juga bisa mengakses properti menggunakan nilai string yang disimpan dalam variabel:

- -
var propertyName = 'make';
-myCar[propertyName] = 'Ford';
-
-propertyName = 'model';
-myCar[propertyName] = 'Mustang';
- -

Kamu bisa menggunakan notasi kurung siku dengan for...in untuk mengiterasi ulang semua kumpulan properti yang terdaftar dari sebuah objek. Untuk mengilustrasikan cara kerjanya, fungsi berikut ini menampilkan properti dari objek ketika kamu memasukkan objek dan nama objek sebagai argumen pada fungsi:

- -
function showProps(obj, objName) {
-  var result = '';
-  for (var i in obj) {
-    // obj.hasOwnProperty() digunakan untuk menyaring properti dari rantai prototipe objek
-    if (obj.hasOwnProperty(i)) {
-      result += objName + '.' + i + ' = ' + obj[i] + '\n';
-    }
-  }
-  return result;
-}
-
- -

Jadi memanggil fungsi showProps(mobilKu, "mobilKu") akan mengembalikan:

- -
myCar.make = Ford
-myCar.model = Mustang
-myCar.year = 1969
- -

Mengenumerasi properti dari objek

- -

Mulai ECMAScript 5, ada tiga cara asli untuk mendaftarkan/melintasi properti objek:

- - - -

Sebelum ECMAScript 5, tidak ada cara asli untuk mendaftarkan semua properti-properti dari suatu objek. Namun, ini dapat dicapai dengan fungsi berikut:

- -
function listAllProperties(o) {
-	var objectToInspect;
-	var result = [];
-
-	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) {
-      result = result.concat(Object.getOwnPropertyNames(objectToInspect));
-	}
-
-	return result;
-}
-
- -

Ini dapat berguna untuk memperlihatkan properti-properti  tersembunyi" (properti-properti dalam rantai prototip yang tidak dapat diakses melalui objek, karena properti lain memiliki nama yang sama di rantai prototip sebelumnya). Mendaftarkan properti-properti yang dapat diakses hanya dapat dilakukan dengan menghapus duplikat di dalam array.

- -

Membuat objek baru

- -

JavaScript mempunyai sejumlah objek yang telah ditetapkan. Selain itu, kamu dapat membuat objek sendiri. Kamu bisa membuat sebuah objek menngunakan sebuah object initializer. Sebagai alternatif, kamu bisa membuat sebuah fungsi konstruktor lalu menginstanisasi sebuah pemanggilan objek bersama dengan operator new.

- -

Menggunakan object initializer

- -

Selain membuat objek menggunakan fungsi konstruktor, kamu bisa membuat objek memakai object initializer. Kadang pemakaian object initializer disamakan dengan pembuatan objek dengan notasi literal. "Object initializer" sama dengan terminologi dalam C++.

- -

Syntax untuk objek yang menggunakan object initializer ialah:

- -
var obj = { property_1:   value_1,   // property_# bisa berupa identifier...
-            2:            value_2,   // atau angka...
-            // ...,
-            'property n': value_n }; // atau string
-
- -

Di mana obj adalah nama objek baru, setiap property_i adalah identifier (baik nama, angka, atau string literal), dan setiap value_i adalah expresi yang nilainya diassign ke property_i.  obj dan assignment adalah opsional, jika kamu tidak butuh rujukan ke objek ini, kamu tak usah mengassign dia ke variabel. (Ingat bahwa kamu harus membungkus literal objek dalam tanda kurung jika objeknya muncul dalam statement diharapkan, supaya bisa membedakan mana literal dan mana statement blok.)

- -

Object initializer adalah expresi, dan setiap object initializer mengembalikan objek baru. Objek baru dibuat saat ia muncul dalam statement yang dieksekusi. Object initializer yang identik membuat objek berbeda yang tidak akan sama bila dibandingkan. Objek dibuat seolah-olah ada panggilan new Object(); yaitu, objek yang dibuat dari expresi literal objek adalah instance dari Object.

- -

Statement berikut membuat objek dan mengassign dia ke variabel x jika dan hanya jika expresi cond benar:

- -
if (cond) var x = {greeting: 'hi there'};
-
- -

Contoh berikut membuat myHonda dengan tiga properti. Ingat bahwa properti engine juga adalah objek yang punya properti sendiri.

- -
var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
-
- -

Kamu juga bisa menggunakan object initializer untuk membuat array. Lihat literal array.

- -

Menggunakan fungsi konstruktor

- -

Kamu bisa membuat objek dengan dua langkah alternatif ini:

- -
    -
  1. Definisikan tipe objek dengan menulis fungsi konstruktor. Ada konvensi dengan alasan bagus untuk menggunakan huruf kapital inisial.
  2. -
  3. Membuat instance objek dengan new.
  4. -
- -

Untuk mendefinisi tipe objek, buat fungsi untuk tipe objek tersebut yang menspesifikasi nama, properti, dan metodenya. Misalnya, kamu ingin membuat tipe objek untuk mobil. Kamu ingin jenis objek ini disebut Car, dan kamu ingin punya properti pembuat, model, dan tahun. Untuk melakukan ini, kamu akan menulis fungsi berikut:

- -
function Car(make, model, year) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-}
- -

Perhatikan penggunaan this untuk mengassign nilai ke properti objek berdasarkan nilai yang diteruskan kepada fungsi.

- -

Sekarang kamu bisa membuat objek myCar sebagai berikut:

- -
var mycar = new Car('Eagle', 'Talon TSi', 1993);
- -

Statement ini membuat myCar dan mengassign ia nilai spesifik untuk propertinya. Lalu nilai dari myCar.make ialah string "Eagle", myCar.year ialah integer 1993, dan seterusnya.

- -

Kamu bisa membuat sejumlah objek Car dengan memanggil new. Sebagai contoh.

- -
var kenscar = new Car('Nissan', '300ZX', 1992);
-var vpgscar = new Car('Mazda', 'Miata', 1990);
- -

Objek bisa punya properti yang merupakan objek lain. Misalnya, kamu mendefinisi objek person sebagai berikut:

- -
function Person(name, age, sex) {
-  this.name = name;
-  this.age = age;
-  this.sex = sex;
-}
- -

dan kemudian menginstantiasi dua objek person baru sebagai berikut:

- -
var rand = new Person('Rand McKinnon', 33, 'M');
-var ken = new Person('Ken Jones', 39, 'M');
- -

Kemudian, kamu bisa menulis ulang definisi Car untuk memasukkan properti owner yang mengambil objek person sebagai berikut:

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-}
- -

Untuk menginstantiasi objek baru, gunakan ini:

- -
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
-var car2 = new Car('Nissan', '300ZX', 1992, ken);
- -

Perhatikan bahwa ketimbang meneruskan nilai string atau integer literal ketika membuat objek baru, statement diatas meneruskan objek rand dan ken sebagai argumen untuk pemilik. Lalu jika kamu mau mencari nama pemilik car2, kamu bisa mengakses properti berikut:

- -
car2.owner.name
-
- -

Ingat bahwa kamu selalu bisa menambah properti ke objek yang sudah dibuat sebelumnya. Contohnya statement

- -
car1.color = 'black';
-
- -

menambah properti color pada car1, dan mengassign nilai "black". Ini tak mempengaruhi objek lain. Untuk menambah properti baru ke semua objek dari tipe yang sama, kamu harus menambah properti pada definisi tipe objek Car.

- -

Menggunakan metode Object.create

- -

Objek bisa juga dibuat menggunakan metode {{jsxref("Object.create()")}}. Metode ini bisa sangat berguna, karena ia memungkinkan kamu memilih prototipe objek untuk objek yang mau kamu buat, tanpa harus mendefinisi fungsi konstruktor.

- -
// Enkapsulasi metode dan properti Animal
-var Animal = {
-  type: 'Invertebrates', // Nilai properti default
-  displayType: function() {  // Method which will display type of Animal
-    console.log(this.type);
-  }
-};
-
-// Create new animal type called animal1 
-var animal1 = Object.create(Animal);
-animal1.displayType(); // Output:Invertebrates
-
-// Create new animal type called Fishes
-var fish = Object.create(Animal);
-fish.type = 'Fishes';
-fish.displayType(); // Output:Fishes
- -

Warisan

- -

Semua objek di javascript diwariskan setidaknya dari satu objek lain. Objek yang diwariskan disebut prototipe, dan properti warisan bisa ditemukan dalam objek prototype dari konstruktor. Lihat Rantai warisan dan prototype untuk informasi lebih lanjut.

- -

Mengindex properti objek

- -

Kamu dapat merujuk ke properti dari objek menggunakan nama propertinya ataupun index urutannya. Jika kamu awalnya mendefinisi properti memakai namanya, kamu harus selalu merujuknya dengan namanya, dan jika kamu awalnya mendefinisikan properti memakai index, kamu harus selalu merujuknya dengan indexnya.

- -

Pembatasan ini berlaku ketika kamu membuat objek dan propertinya dengan fungsi konstruktor (seperti yang kita lakukan sebelumnya dengan jenis objek Car) dan ketika kamu mendefinisi properti individual secara explisit (misalnya, myCar.color = "ref"). Jika kamu awalnya mendefinisi properti objek dengan index, seperti myCar[5] = "25 mpg", maka kamu merujuk ke properti tersebut dengan myCar[5].

- -

Pengecualian dalam aturan ini adalah objek mirip-array pantulan dari HTML, seperti objek mirip-array forms. Kamu selalu dapat merujuk ke objek dalam objek mirip-array ini menggunakan nomor urutan mereka (berdasarkan di mana mereka muncul dalam dokumen) atau nama mereka (jika didefinisi). Misalnya, jika tag <FORM> kedua dalam dokumen punya atribut NAME "myForm", kamu dapat merujuk ke form tersebut sebagai document.forms[1] atau document.forms["myForm"] atau document.forms.myForm.

- -

Mendefinisi properti untuk tipe objek

- -

Kamu dapat menambah properti ke tipe objek yang didefinisi sebelumnya menggunakan properti prototype. Ini mendefinisi properti yang dibagikan semua objek dari tipe yang dispesifikasi, bukan cuma satu instance objek. Kode berikut menambahkan sebuah properti color ke semua objek dari tipe objek Car, dan kemudian mengassign nilai ke properti color dari objek car1.

- -
Car.prototype.color = null;
-car1.color = 'black';
- -

Lihat properti prototipe dari objek Function dalam referensi JavaScript untuk informasi lebih lanjut.

- -

Mendefiniskan metode

- -

Metode ialah fungsi yang terasosiasi dengan objek, atau sederhananya, metode ialah properti dari objek berupa fungsi. Metode didefinisi sebagai cara fungsi nornal didefinisi, kecuali mereka harus diassign sebagai properti objek. Lihat juga definisi metode untuk lebih detil. Contohnya:

- -
objectName.methodname = functionName;
-
-var myObj = {
-  myMethod: function(params) {
-    // ...do something
-  }
-
-  // OR THIS WORKS TOO
-
-  myOtherMethod(params) {
-    // ...do something else
-  }
-};
-
- -

Di mana objectName adalah metode yang sudah ada, methodname ialah nama yang kamu assign ke metode, dan functionName adalah nama fungsi.

- -

Lalu kamu bisa memanggil metode dalam kontex objek sebagai berikut:

- -
object.methodname(params);
-
- -

Kamu bisa mendefinisi metode untuk tipe objek dengan memasukkan sebuah definisi metode dalam fungsi konstruktor objek. Kamu bisa mendefinisi fungsi yang akan memformat dan menampilkan properti objek Car sebelumnya; contohnya,

- -
function displayCar() {
-  var result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
-  pretty_print(result);
-}
- -

Di mana pretty_print adalah fungsi untuk menampilkan garis horizontal dan string. Perhatikan penggunaan this untuk merujuk ke objek yang punya metode tersebut.

- -

Kamu bisa menjadikan fungsi ini metode Car dengan menambah statement

- -
this.displayCar = displayCar;
- -

ke definisi objek. Jadi definisi penuh dari Car sekarang akan terlihat seperti

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-  this.displayCar = displayCar;
-}
- -

Maka kamu bisa memanggil metode displayCar untuk masing-masig objek sebagai berikut:

- -
car1.displayCar();
-car2.displayCar();
- -

Menggunakan this untuk referensi Objek

- -

JavaScript punya katakunci spesial this, kamu bisa memakainya dalam metode untuk merujuk ke objek saat ini. Misalnya, kamu punya fungsi yang disebut validate yang memvalidasi properti value, yang diberikan objek dan nilai atas dan bawah:

- -
function validate(obj, lowval, hival) {
-  if ((obj.value < lowval) || (obj.value > hival)) {
-    alert('Invalid Value!');
-  }
-}
-
- -

Kemudian kamu bisa panggil validate di penangan event onchange setiap elemen form, gunakan this untuk meneruskan elemen. Seperti contoh berikut:

- -
<input type="text" name="age" size="3"
-  onChange="validate(this, 18, 99)">
-
- -

Secara umum, this merujuk ke pemanggilan objek dalam metode.

- -

Ketika dikombinasikan dengan properti form, this bisa mengacu ke induk objek form saat ini. Dalam contoh berikut, form myForm berisi objek Text dan sebuah tombol. Ketika pengguna mengklik tombol, nilai objek Text diset ke nama form tersebut. Penangan event onclick tombol menggunakan this.form untuk merujuk ke induk form, myForm.

- -
<form name="myForm">
-<p><label>Form name:<input type="text" name="text1" value="Beluga"></label>
-<p><input name="button1" type="button" value="Show Form Name"
-     onclick="this.form.text1.value = this.form.name">
-</p>
-</form>
- -

Mendefinisikan getter dan setter

- -

Getter ialah metode yang mendapat nilai dari properti spesifik. Setter ialah metode yang mengatur nilai properti spesifik. Kamu bisa mendefinisi getter dan setter objek inti apapun yang sudah ditetapkan atau objek yang ditetapkan pengguna yang mendukung penambahan peroperti-properti baru. Syntax untuk mendefinisi getter dan setter menggunakan syntax literal objek.

- -

Berikut ilustrasi cara getter dan setter bisa bekerja untuk objek o yang sudah didefinisi user.

- -
var o = {
-  a: 7,
-  get b() {
-    return this.a + 1;
-  },
-  set c(x) {
-    this.a = x / 2;
-  }
-};
-
-console.log(o.a); // 7
-console.log(o.b); // 8
-o.c = 50;
-console.log(o.a); // 25
-
- -

Properti objek o adalah:

- - - -

Harap diingat bahwa nama fungsi dari getter dan setter yang didefisini dalam literal objek menggunakan "[gs]et property()" (dibandingkan dengan __define[GS]etter__ ) bukanlah nama getter mereka sendiri, meski syntax [gs]et propertyName(){ } membuatmu berpikir lain. Untuk menamai fungsi dalam getter atau setter menggunakan syntax "[gs]et property()", definiskan fungsi, dengan nama explisit, secara terprogram menggunakan Object.defineProperty (atau pengganti legacy Object.prototype.__defineGetter__).

- -

Kode berikut mengilustrasikan cara getter dan setter bisa memperluas prototipe {{jsxref("Date")}} untuk menambah properti year ke semua instance dari kelas Date yang sudah didefinisi. Ia menggunakan metode kelas Date yang sudah ada, getFullYear dan setFullYear untuk mendukung properti getter dan setter year.

- -

Statement ini mendefinisi getter dan setter untuk properti tahun:

- -
var d = Date.prototype;
-Object.defineProperty(d, 'year', {
-  get: function() { return this.getFullYear(); },
-  set: function(y) { this.setFullYear(y); }
-});
-
- -

Statement ini menggunakan getter dan setter dalam objek Date:

- -
var now = new Date();
-console.log(now.year); // 2000
-now.year = 2001; // 987617605170
-console.log(now);
-// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
-
- -

Secara pinsip, getter dan setter bisa

- - - -

Ketika mendefiniisi getter dan setter menggunakan object initializer yang harus kamu lakukan adalah memprefix metode getter dengan get dan metode setter dengan set. Tentunya, metode getter tidak boleh mengharapkan parameter, lalu metode setter mengharapkan hanya satu parameter (nilai baru untuk diset). Contohnya:

- -
var o = {
-  a: 7,
-  get b() { return this.a + 1; },
-  set c(x) { this.a = x / 2; }
-};
-
- -

Getter dan setter juga bisa ditambah ke objek kapanpun setelah membuat objek menggunakan metode Object.defineProperties. Parameter pertama metode ini ialah object tempat kamu mendefinisi getter atau setter. Parameter kedua ialah objek yang nama propertinya berupa nama getter atau setter,dan yang nilai propertinya berupa objek yang mendefinisi fungsi getter atau setter. Berikut adalah contoh mendefinisi getter dan setter yang sama yang digunakan dalam contoh sebelumnya:

- -
var o = { a: 0 };
-
-Object.defineProperties(o, {
-    'b': { get: function() { return this.a + 1; } },
-    'c': { set: function(x) { this.a = x / 2; } }
-});
-
-o.c = 10; // Menjalankan setter, yang mengassign 10 / 2 (5) ke properti 'a'
-console.log(o.b); // Menjalankan getter, yang menghasilkan a + 1 atau 6
-
- -

Yang manapun dari dua form ini yang dipilih tergantung dari gaya pemrograman dan tugas di tangan. Jika kamu sudah memilih object initializer ketika mendefinisi prototipe kamu mungkin akan sering memilih form pertama. Form ini lebih compact dan natural. Namun, kalau kamu harus menambah getter dan setter nanti — karena kamu tak menulis prototipenya atau object khusus — maka form kedua menjadi satu-satunya solusi. Form kedua mungkin paling baik mewakiliki sifat dinamis JavaScript — tapi ia bisa membuat kode sulit dibaca dan dipahami.

- -

Menghapus properti

- -

Kamu bisa menghapus properti yang bukan warisan menggunakan operator delete. Kode berikut menampilkan cara menghapus properti.

- -
// Membuat objek baru, myobj, dengan dua properti, a dan b.
-var myobj = new Object;
-myobj.a = 5;
-myobj.b = 12;
-
-// Mengapus properti a, menyisakan myobj hanya dengan properti b.
-delete myobj.a;
-console.log ('a' in myobj); // menghasilkan "false"
-
- -

Kamu juga bisa memakai delete untuk menghapus variabel global jika katakunci var tidak dipakai untuk mendeklarasi variabel itu:

- -
g = 17;
-delete g;
-
- -

Membandingkan objek

- -

Dalam JavaScript objek ialah tipe referensi. Dua objek berbeda tak akan pernah sama, meski mereka punya properti yang sama. Hanya membandingkan referensi objek yang sama dengannya menghasilkan true.

- -
// Dua variabel, dua objek berbeda dengan properti yang sama
-var fruit = {name: 'apple'};
-var fruitbear = {name: 'apple'};
-
-fruit == fruitbear; // mengembalikan false
-fruit === fruitbear; // mengembalikan false
- -
// Dua variabel, objek tunggal
-var fruit = {name: 'apple'};
-var fruitbear = fruit;  // assign referensi objek buah ke fruitbear
-
-// di sini fruit dan fruitbear menunjuk ke objek yang sama
-fruit == fruitbear; // mengembalikan true
-fruit === fruitbear; // mengembalikan true
-
- -
fruit.name = 'grape';
-console.log(fruitbear);    // menghasilkan { name: "grape" } ketimbang { name: "apple" }
-
- -

Untuk informasi lebih tentang operator pembandingan, lihat Operator pembandingan.

- -

Lihat juga

- - - -

{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}

diff --git a/files/id/web/javascript/index.html b/files/id/web/javascript/index.html deleted file mode 100644 index bfc6233ce4..0000000000 --- a/files/id/web/javascript/index.html +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: JavaScript -slug: Web/JavaScript -tags: - - JavaScript - - belajar -translation_of: Web/JavaScript ---- -
{{JsSidebar}}
- -

JavaScript (JS) sangat ringan, terinterpretasi, bahasa pemrogramman dengan first-class functions. Umum dikenal sebagai bahasa scripting untuk halaman web, Banyak lingkungan non-browser juga menggunakan javascript, seperti node.js dan Apache CouchDB. JS merupakan prototype-based, multi-paradigm, bahasa scripting dinamis, medukung object-oriented, diperlukan, dan declarative (mis. functional programming) styles. Baca lebih lanjut about JavaScript.

- -

Bagian situs ini didedikasikan untuk bahasa javascript dan bukan bagian yang spesifik dengan halaman web atau lingkungan host lain. Untuk informasi tentang {{Glossary("API","APIs")}} yang spesifik untuk halaman web, Lihat Web APIs dan DOM.

- -

Standar untuk JavaScript adalah ECMAScript. Seperti pada 2012, semua modern browsers mendukung ECMAScript 5.1. Browser lama mendukung setidaknya  ECMAScript 3. Juni 17, 2015, ECMA International mempublikasikan versi major keenam dari ECMAScript, yang secara ofisial disebut ECMAScript 2015, dan umumnya dikaitkan sebagai ECMAScript 6 atau ES6. Sejak ketika standar ECMAScript pada siklus rilis tahunan. Dokumentasi ini mengacu pada draft versi terbaru, saat ini ECMAScript 2018.

- -

Jangan keliru antara JavaScript dengan Bahasa pemrograman java. Keduanya "Java" dan "JavaScript" adalah merek dagang dan merek ini terdaftar oleh Oracle di U.S. dan negara lainnya. Namun, kedua bahasa pemrograman tersebut memiliki sintaks, struktur, dan penggunaan yang berbeda.

- -
-
-

Tutorial

- -

Belajar cara menulis program di javascript dengan paduan dan tutorial.

- -

Untuk Pemula

- -

Pergilah ke topik Area Pembelajaran JavaScript kami jika Anda ingin belajar JavaScript dan belum memiliki pengalaman dari pemrograman JavaScript. Tersedia modul lengkap sebagai berikut:

- -

Langkah pertama JavaScript
-      Jawaban beberapa pertanyaan mendasar seperti "apa itu JavaScript?", "Seperti apa tampilannya?", Dan "apa yang bisa dilakukan?", Bersama mendiskusikan fitur utama JavaScript seperti variabel, string, angka dan array.

- -

Bangunan Blok JavaScript
-     Lanjutan jangkauan dari fitur dasar kunci JavaScript, arahkan perhatian pada jenis blok kode yang biasa ditemukan seperti statement kondisional, loop, fungsi, dan events.

- -

Perkenalan Objek JavaScript
-      Sifat JavaScript yang berorientasi objek penting untuk dipahami jika Anda ingin melangkah lebih jauh dengan pengetahuan Anda tentang bahasanya dan menulis kode yang lebih efisien, oleh karena itu kami menyediakan modul ini untuk membantu Anda.

- -

Pengantar

- -
-
Paduan JavaScript
-
Jika anda baru mengenal javascript, paduan ini akan menuntun anda belajar.
-
Ikhtisar Teknologi JavaScript
-
Pengantar javascript pada lingkungan web browser.
-
Pengantar JavaScript Berbasis Objek
-
Pengantar pada konsep dari bahasa berorientasi object di JavaScript.
-
- -

Menengah

- -
-
Mengenal kembali JavaScript
-
Gambaran bagi mereka yang berfikir mengetahui tentang JavaScript.
-
- -
-
Struktur data JavaScript
-
Gambaran struktur data yang tersedia di JavaScript.
-
Perbandingan kesetaraan dan kesamaan
-
JavaScript  menyediakan tiga operasi perbandingan yang berbeda: perbandingan stric ===, perbandingan loggar menggunakan ==, dan method {{jsxref("Global_Objects/Object/is", "Object.is()")}}.
-
- -

Lanjut

- -
-
Pewarisan dan rantai purwarupa
-
Menjelaskan tentang kesalah-pahaman dan meremehkan yang terjadi pada  pewarisan berbasis purwarupa.
-
Mode Strict
-
Mode strict mendefinisikan bahwa anda tidak dapat menggunakan variabel sebelum menginisialisasinya. Ini bentuk batasan dari varian ECMAScript 5, berguna untuk performa yang lebih cepat dan debuging yang lebih mudah.
-
JavaScript typed arrays
-
JavaScript typed arrays menyediakan mekanisme untuk mengakses data binari mentah(raw).
-
Pengelolaan Memory
-
Siklus memori dan garbage collection di JavaScript.
-
Model konkurensi dan Event Loop
-
JavaScript memiliki model konkurensi berbasis pada "event loop".
-
-
- -
-

Referensi

- -

Jelajahi dokumentasi Referensi javaScript.

- -
-
Standard objects
-
Mencari tahu tentang standarbuilt-in objects {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}},{{jsxref("RegExp")}} , {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}} , {{jsxref("WeakSet")}}, dan lainnya.
-
Ekspresi dan operator
-
Belajar tentang cara kerja operator {{jsxref("Operators/instanceof", "instanceof")}},  {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}},  operator precedence, dan banyak lagi.
-
Statemen dan pendeklarasian
-
Belajar cara menggunakan {{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}}, dan statement Javascript lain dan juga kerja keywords.
-
 Fungsi
-
Belajar bagaimana menggunakan fugsi untuk digunakan di aplikasi anda.
-
- -

Alat & sumber

- -

Alat yang dapat membantu anda menulis dan mendebug kode JavaScript.

- -
-
Firefox Developer Tools
-
Scratchpad, Web Console, JavaScript Profiler, Debugger, dan lainnya.
-
Firebug
-
Edit, debug, dan melihat CSS, HTML, juga JavaScript langsung di setiap halaman web.
-
JavaScript Shells
-
JavaScript shell memungkinkan anda untuk mencoba kode snippet JavaScript.
-
TogetherJS
-
Mempermudah kolaborasi.
-
Stack Overflow
-
Bertanya di Stack Overflow dengan tag "JavaScript".
-
Versi JavaScript dan catatan release
-
Jelajahi sejarah fitur JavaScript dan status implementasi.
-
JSFiddle
-
Edit JavaScript, CSS, HTML dan lihat secara langsung. Gunakan sumber dari luar dan berkolaborasi dengan tim anda secara online.
-
-
-
diff --git a/files/id/web/javascript/inheritance_and_the_prototype_chain/index.html b/files/id/web/javascript/inheritance_and_the_prototype_chain/index.html deleted file mode 100644 index 851bcbbb21..0000000000 --- a/files/id/web/javascript/inheritance_and_the_prototype_chain/index.html +++ /dev/null @@ -1,305 +0,0 @@ ---- -title: Inheritance dan prototype chain -slug: Web/JavaScript/Inheritance_and_the_prototype_chain -translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain -original_slug: Web/JavaScript/Inheritance_dan_prototype_chain ---- -
{{jsSidebar("Advanced")}}
- -

JavaScript sedikit membingungkan bagi pengembang yang berpengalaman di pemrograman berbasis class (seperti java dan C++), sebagai bahasa dinamis dan tidak mendukung implementasi class lihat( keyword class dikenalkan pada ES2015, namun terkesan berlebihan, JavaScript merupakan bahasa berbasis prototype).

- -

Ketika menggunakan inheritance, JavaScript hanya memiliki satu construct: objek. Setiap objek memiliki sebuah private property ( berkenaan tentang [[Prototype]] ) yang memegang jalinan ke objek lain yang memanggil prototype tersebut. Prototype objek tersebut memiliki prototype sendiri, dan seterusnya hingga objek mencapai prototipe null. Dengan definisi, null tidak lagi memiliki prototype, dan berperan sebagai hubungan terakhir dari prototype chain.

- -

Hampir seluruh objek pada JavaScript merupakan instance dari {{jsxref("Object")}} dimana berada di atas prototype chain.

- -

Meskipun hal ini sering dianggap sebagai salah satu kelemahan JavaScript, model Inheritance prototype sebenarnya lebih hebat daripada model klasiknya. Hal ini, misalnya, cukup sepele untuk membangun model klasik di atas model prototipal.

- -

Inheritance dengan prototype chain

- -

Meng-Inheriting properti

- -

JavaScript objects are dynamic "bags" of properties (referred to as own properties). JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

- -
-

Following the ECMAScript standard, the notation someObject.[[Prototype]] is used to designate the prototype of someObject. Since ECMAScript 2015, the [[Prototype]] is accessed using the accessors {{jsxref("Object.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}}. This is equivalent to the JavaScript property __proto__ which is non-standard but de-facto implemented by many browsers.

- -

It should not be confused with the func.prototype property of functions, which instead specifies the [[Prototype]] to be assigned to all instances of objects created by the given function when used as a constructor. The Object.prototype property represents the {{jsxref("Object")}} prototype object.

-
- -

Here is what happens when trying to access a property:

- -
// Let's assume we have object o, with its own properties a and b:
-// {a: 1, b: 2}
-// o.[[Prototype]] has properties b and c:
-// {b: 3, c: 4}
-// Finally, o.[[Prototype]].[[Prototype]] is null.
-// This is the end of the prototype chain, as null,
-// by definition, has no [[Prototype]].
-// Thus, the full prototype chain looks like:
-// {a: 1, b: 2} ---> {b: 3, c: 4} ---> null
-
-console.log(o.a); // 1
-// Is there an 'a' own property on o? Yes, and its value is 1.
-
-console.log(o.b); // 2
-// Is there a 'b' own property on o? Yes, and its value is 2.
-// The prototype also has a 'b' property, but it's not visited.
-// This is called "property shadowing."
-
-console.log(o.c); // 4
-// Is there a 'c' own property on o? No, check its prototype.
-// Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4.
-
-console.log(o.d); // undefined
-// Is there a 'd' own property on o? No, check its prototype.
-// Is there a 'd' own property on o.[[Prototype]]? No, check its prototype.
-// o.[[Prototype]].[[Prototype]] is null, stop searching,
-// no property found, return undefined.
-
- -

Setting a property to an object creates an own property. The only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter.

- -

Inheriting "methods"

- -

JavaScript does not have "methods" in the form that class-based languages define them. In JavaScript, any function can be added to an object in the form of a property. An inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of method overriding).

- -

When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.

- -
var o = {
-  a: 2,
-  m: function() {
-    return this.a + 1;
-  }
-};
-
-console.log(o.m()); // 3
-// When calling o.m in this case, 'this' refers to o
-
-var p = Object.create(o);
-// p is an object that inherits from o
-
-p.a = 4; // creates an own property 'a' on p
-console.log(p.m()); // 5
-// when p.m is called, 'this' refers to p.
-// So when p inherits the function m of o,
-// 'this.a' means p.a, the own property 'a' of p
-
- -

Different ways to create objects and the resulting prototype chain

- -

Objects created with syntax constructs

- -
var o = {a: 1};
-
-// The newly created object o has Object.prototype as its [[Prototype]]
-// o has no own property named 'hasOwnProperty'
-// hasOwnProperty is an own property of Object.prototype.
-// So o inherits hasOwnProperty from Object.prototype
-// Object.prototype has null as its prototype.
-// o ---> Object.prototype ---> null
-
-var b = ['yo', 'whadup', '?'];
-
-// Arrays inherit from Array.prototype
-// (which has methods indexOf, forEach, etc.)
-// The prototype chain looks like:
-// b ---> Array.prototype ---> Object.prototype ---> null
-
-function f() {
-  return 2;
-}
-
-// Functions inherit from Function.prototype
-// (which has methods call, bind, etc.)
-// f ---> Function.prototype ---> Object.prototype ---> null
-
- -

With a constructor

- -

A "constructor" in JavaScript is "just" a function that happens to be called with the new operator.

- -
function Graph() {
-  this.vertices = [];
-  this.edges = [];
-}
-
-Graph.prototype = {
-  addVertex: function(v) {
-    this.vertices.push(v);
-  }
-};
-
-var g = new Graph();
-// g is an object with own properties 'vertices' and 'edges'.
-// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.
-
- -

With Object.create

- -

ECMAScript 5 introduced a new method: {{jsxref("Object.create()")}}. Calling this method creates a new object. The prototype of this object is the first argument of the function:

- -
var a = {a: 1};
-// a ---> Object.prototype ---> null
-
-var b = Object.create(a);
-// b ---> a ---> Object.prototype ---> null
-console.log(b.a); // 1 (inherited)
-
-var c = Object.create(b);
-// c ---> b ---> a ---> Object.prototype ---> null
-
-var d = Object.create(null);
-// d ---> null
-console.log(d.hasOwnProperty);
-// undefined, because d doesn't inherit from Object.prototype
-
- -
-

With the class keyword

- -

ECMAScript 2015 introduced a new set of keywords implementing classes. Although these constructs look like those familiar to developers of class-based languages, they are not the same. JavaScript remains prototype-based. The new keywords include {{jsxref("Statements/class", "class")}}, {{jsxref("Classes/constructor", "constructor")}}, {{jsxref("Classes/static", "static")}}, {{jsxref("Classes/extends", "extends")}}, and {{jsxref("Operators/super", "super")}}.

- -
'use strict';
-
-class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
-
-class Square extends Polygon {
-  constructor(sideLength) {
-    super(sideLength, sideLength);
-  }
-  get area() {
-    return this.height * this.width;
-  }
-  set sideLength(newLength) {
-    this.height = newLength;
-    this.width = newLength;
-  }
-}
-
-var square = new Square(2);
-
- -

Performance

- -

The lookup time for properties that are high up on the prototype chain can have a negative impact on performance, and this may be significant in code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain.

- -

Also, when iterating over the properties of an object, every enumerable property that is on the prototype chain will be enumerated.To check whether an object has a property defined on itself and not somewhere on its prototype chain, it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype. To give you a concrete example, let's take the above graph example code to illustrate it:

- -
console.log(g.hasOwnProperty('vertices'));
-// true
-
-console.log(g.hasOwnProperty('nope'));
-// false
-
-console.log(g.hasOwnProperty('addVertex'));
-// false
-
-console.log(g.__proto__.hasOwnProperty('addVertex'));
-// true
-
- -

hasOwnProperty is the only thing in JavaScript which deals with properties and does not traverse the prototype chain.

- -

Note: It is not enough to check whether a property is undefined. The property might very well exist, but its value just happens to be set to undefined.

-
- -

Bad practice: Extension of native prototypes

- -

One mis-feature that is often used is to extend Object.prototype or one of the other built-in prototypes.

- -

This technique is called monkey patching and breaks encapsulation. While used by popular frameworks such as Prototype.js, there is still no good reason for cluttering built-in types with additional non-standard functionality.

- -

The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines, like Array.forEach.

- -

Example

- -

B shall inherit from A:

- -
function A(a) {
-  this.varA = a;
-}
-
-// What is the purpose of including varA in the prototype when A.prototype.varA will always be shadowed by
-// this.varA, given the definition of function A above?
-A.prototype = {
-  varA: null,  // Shouldn't we strike varA from the prototype as doing nothing?
-      // perhaps intended as an optimization to allocate space in hidden classes?
-      // https://developers.google.com/speed/articles/optimizing-javascript#Initializing-instance-variables
-      // would be valid if varA wasn't being initialized uniquely for each instance
-  doSomething: function() {
-    // ...
-  }
-};
-
-function B(a, b) {
-  A.call(this, a);
-  this.varB = b;
-}
-B.prototype = Object.create(A.prototype, {
-  varB: {
-    value: null,
-    enumerable: true,
-    configurable: true,
-    writable: true
-  },
-  doSomething: {
-    value: function() { // override
-      A.prototype.doSomething.apply(this, arguments); // call super
-      // ...
-    },
-    enumerable: true,
-    configurable: true,
-    writable: true
-  }
-});
-B.prototype.constructor = B;
-
-var b = new B();
-b.doSomething();
-
- -

The important parts are:

- - - -

prototype and Object.getPrototypeOf

- -

JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object.

- -

You probably already noticed that our function A has a special property called prototype. This special property works with the JavaScript new operator. The reference to the prototype object is copied to the internal [[Prototype]] property of the new instance. For example, when you do var a1 = new A(), JavaScript (after creating the object in memory and before running function A() with this defined to it) sets a1.[[Prototype]] = A.prototype. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. This means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances, if you wanted to.

- -

If, in the example above, you do var a1 = new A(); var a2 = new A(); then a1.doSomething would actually refer to Object.getPrototypeOf(a1).doSomething, which is the same as the A.prototype.doSomething you defined, i.e. Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething.

- -

In short, prototype is for types, while Object.getPrototypeOf() is the same for instances.

- -

[[Prototype]] is looked at recursively, i.e. a1.doSomething, Object.getPrototypeOf(a1).doSomething, Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething etc., until it's found or Object.getPrototypeOf returns null.

- -

So, when you call

- -
var o = new Foo();
- -

JavaScript actually just does

- -
var o = new Object();
-o.[[Prototype]] = Foo.prototype;
-Foo.call(o);
- -

(or something like that) and when you later do

- -
o.someProp;
- -

it checks whether o has a property someProp. If not, it checks Object.getPrototypeOf(o).someProp, and if that doesn't exist it checks Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp, and so on.

- -
-

In conclusion

- -

It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features.

-
diff --git a/files/id/web/javascript/javascript_technologies_overview/index.html b/files/id/web/javascript/javascript_technologies_overview/index.html deleted file mode 100644 index c988092b23..0000000000 --- a/files/id/web/javascript/javascript_technologies_overview/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Ikhtisar Teknologi JavaScript -slug: Web/JavaScript/JavaScript_technologies_overview -translation_of: Web/JavaScript/JavaScript_technologies_overview -original_slug: Web/JavaScript/sekilas_teknologi_JavaScript ---- -
{{JsSidebar("Introductory")}}
- -

Pengantar

- -

Jika HTML untuk mengatur struktur dan konten dari halaman web dan CSS untuk menetapkan format dan tampilannya, maka JavaScript digunakan untuk menambah interaksi pada halaman web dan menciptakan aplikasi web yang kaya.

- -

Namun, istilah "JavaScript" seperti yang dikenal pada konteks browser web berisi beberapa elemen yang sangat berbeda. Salah satunya adalah bahasa intinya (ECMAScript), yang lainnya adalah koleksi dari Web APIs, termasuk DOM (Document Object Model).

- -

Bahasa inti (ECMAScript) JavaScript

- -

Bahasa inti dari JavaScript distandarisasi oleh komite ECMA TC39 sebagai bahasa yang bernama ECMAScript.

- -

Bahasa inti ini juga digunakan pada lingkungan non-browser, misalnya node.js.

- -

Apa yang termasuk dalam lingkup ECMAScript?

- -

Diantaranya, ECMAScript menetapkan:

- - - -

Dukungan browser

- -

Pada Oktober 2016, versi terbaru dari sebagian besar browser Web sudah menerapkan ECMAScript 5.1 dan ECMAScript 2015, namun versi yang lebih lama (yang masih digunakan) hanya menerapkan ECMAScript 5.

- -

Masa depan

- -

ECMAScript Edisi ke-6 mayor telah secara resmi disetujui dan diumumkan sebagai standar pada 17 Juni 1015 oleh ECMA General Assembly. Sejak saat itu Edisi ECMAScript diumumkan secara tahunan.

- -

API Internasionalisasi

- -

Spesifikasi API Internasionalisasi ECMAScript merupakan tambahan dari Spesifikasi Bahasa ECMAScript, yang juga distandarisasi oleh Ecma TC39. API internasionalisasi menyediakan kolasi (perbandingan string), format angka, format tanggal dan jam untuk aplikasi JavaScript, memungkinkan aplikasi memilih bahasa dan menyesuaikan fungsi sesuai kebutuhannya. Standar awal telah disetujui pada Desember 2012; status impementasinya dalam browser dicatat di dokumentasi Intl object. Saat ini spesifikasi Internasionalisasi juga disahkan secara tahunan dan browser secara konsisten meningkatkan implementasinya.

- -

API DOM

- -

WebIDL

- -

WebIDL specification memberikan perekat antara teknologi DOM dan ECMAScript.

- -

Inti dari DOM

- -

Document Object Model (DOM) adalah bahasa konvensi independen lintas platform untuk mewakili dan berinteraksi dengan objects dalam dokumen HTML, XHTML dan XML. Objects didalam DOM tree dapat dialamatkan dan dimanipulasi dengan menggunakan methods pada objects. Core Document Object Model yang distandarisasi oleh {{glossary("W3C")}}, menetapkan antarmuka bahasa-agnostik untuk mengabstaraksi dokumen HTML dan XML sebagai objects, dan juga menetapkan mekanisme untuk memanipulasi abstraksi ini. Diantara yang ditetapkan oleh DOM, kita dapat menemukan:

- - - -

Dari sudut pandang ECMAScript, objects yang didefinisikan di spesifikasi DOM disebut "host objects".

- -

HTML DOM

- -

Bahasa markup Web (HTML) yang ditetapkan dari sisi DOM. Seperti dalam konsep abstrak yang dibahas diatas pada Inti DOM, HTML juga didefinisikan sebagai sebuah elemen. The HTML DOM menyertakan properti className pada elemen HTML, or APIs seperti {{ domxref("document.body") }}.

- -

Spesifikasi HTML juga menetapkan batasan pada dokumen; misalnya, ia memerlukan semua elemen anak dari sebuah ul untuk mewakili sebuah daftar tak urut, elemen li untuk mewakili daftar item. Secara umum, ia juga melarang penggunaan elemen dan atribut yang tidak didefinisikan dalam standar.

- -

Ingin mengetahui Document object, Window object, dan elemen DOM lainnya? Baca DOM documentation.

- -

API penting lainnya

- - - -

Dukungan browser

- -

Seperti kata pengembang web yang berpengalaman, DOM berantakan. Dukungan fitur-fitur DOM antar browser bervarasi, terutama disebabkan karena banyak fitur yang penting dari DOM sangat tidak jelas, spesifikasi (jika ada) dan browser web yang berbeda menambahkan fitur yang tidak kompatibel untuk overlapping use cases (misalnya Internet Explorer event model). Pada Juni 2011, W3C dan khususnya WHATWG menetapkan fitur-fitur lama secara rinci untuk meningkatkan interoperabilitas, dan browser pada akhirnya dapat meningkatkan implementasi mereka berdasarkan spesifikasi ini.

- -

Sebuah teknik umum, meskipun mungkin bukan yang paling dapat diandalkan, pendekatan kompatibilitas lintas browser adalah dengan menggunakan pustaka JavaScript, yang menggunakan fitur DOM abstrak untuk menjaga API mereka tetap bekerja di browser yang berbeda. Beberapa framework yang paling banyak digunakan adalah jQuery, prototype, dan YUI.

diff --git a/files/id/web/javascript/language_resources/index.html b/files/id/web/javascript/language_resources/index.html deleted file mode 100644 index bda5fe1f42..0000000000 --- a/files/id/web/javascript/language_resources/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: JavaScript language resources -slug: Web/JavaScript/Language_Resources -tags: - - Advanced - - JavaScript -translation_of: Web/JavaScript/Language_Resources ---- -
{{JsSidebar}}
- -

ECMAScript merupakan bahasa scripting yang membentuk basis dari  JavaScript. ECMAScript di standarisasi oleh organisasi standard ECMA International pada Spesifikasi ECMA-262 dan ECMA-402. Berikut ECMAScript standard yang telah disetujui atau masih dalam pengerjaan:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NamaLinkTanggal rilisDeskripsi
Edisi saat ini
ECMA-262 2017 (ES 8)Working draft, repository2017ECMAScript 2017 (8th Edition), currently work in progress.
ECMA-402 4.0Working draft, repository2017ECMAScript Internationalization API 4.0, currently work in progress.
Obsolete/historical editions
ECMA-262 (ES 1)PDFJune 1997the original ECMAScript standard.
ECMA-262 (ES 2)PDFAugust 1998the second revision of the ECMAScript standard; also ISO standard 16262.
ECMA-262 (ES 3)PDFDecember 1999the third revision of the ECMAScript standard; corresponds to JavaScript 1.5.
- See also the errata
ECMA-262 (ES 5)PDFDecember 2009ECMAScript 5
- See also the ES5 errata and ECMAScript 5 support in Mozilla
ECMA-357PDFJune 2004ECMAScript for XML (E4X).
- See also the E4X errata.
ECMA-357 Edition 2PDFDecember 2005ECMAScript for XML (E4X).
ECMA-262 (ES 5.1)PDF, HTMLJune 2011This version is fully aligned with 3rd edition of the international standard ISO/IEC 16262:2011.
- It includes ES5 errata fixes, no new features.
ECMA-402 1.0PDF, HTMLDecember 2012ECMAScript Internationalization API 1.0.
ECMA-262 2015 (ES 6)PDF, HTMLJune 2015ECMAScript 2015 (6th Edition).
ECMA-402 2.0PDFJune 2015ECMAScript Internationalization API 2.0.
ECMA-262 2016 (ES 7)HTMLJune 2016ECMAScript 2016 (7th Edition). Now feature frozen. To be ratified later this year (June).
ECMA-402 3.0HTMLJune 2016ECMAScript Internationalization API 3.0. To be ratified later this year (June).
- -

Lihat entri Wikipedia ECMAScript untuk info lebih lanjut tentang sejarah ECMAScript.

- -

Anda dapat berpartisipasi atau mengikuti pekerjaan di revisi berikutnya dari spasifikasi bahasa ECMAScript, nama kode "Harmony", dan Spesifikasi ECMAScript Internationalization API melalui public wiki dan es-discuss mailing list tercantum dari ecmascript.org.

- -

Implementasi

- - - -

Lihat juga

- - diff --git a/files/id/web/javascript/memory_management/index.html b/files/id/web/javascript/memory_management/index.html deleted file mode 100644 index 90242f72da..0000000000 --- a/files/id/web/javascript/memory_management/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Memory Management -slug: Web/JavaScript/Memory_Management -translation_of: Web/JavaScript/Memory_Management ---- -
{{JsSidebar("Advanced")}}
- -

Introduction

- -

Bahasa-bahasa Level Bawah, seperti C, memiliki manajemen memory level rendah yang primitiv seperti malloc() dan  free(). Pada bagian lain, nilai Javascript dialokasikan ketika sesuatu (objek, string,dll.) dibuat dan secara otomatis dibebaskan ketika tidak digunakan lagi. Proses terakhir disebut garbage collection. "Secara Otomatis" ini adalah sumber kekeliruan dan memberikan kesan developer Javascript (dan Bahasa tingkat tinggi lainnya) bahwa mereka bisa memilih untuk tidak mempedulikan tentang manajemen memory, maka itu adalah suatu kesalahan

- -

Low-level languages, like C, have low-level memory management primitives like malloc() and free(). On the other hand, JavaScript values are allocated when things (objects, strings, etc.) are created and "automatically" freed when they are not used anymore. The latter process is called garbage collection. This "automatically" is a source of confusion and gives JavaScript (and high-level languages) developers the impression they can decide not to care about memory management. This is a mistake.

- -

Siklus hidup sebuah memori

- -

Tanpa memperhatikan bahasa pemograman, siklus hidup memori pada akhirnya selalu sama :

- -
    -
  1. Mengalokasi memori yang kamu gunakan.
  2. -
  3. Menggunakan alokasi memori untuk (baca, tulis).
  4. -
  5. Membebaskan alokasi memori saat tidak digunakan lagi.
  6. -
- -

Bagian pertama dan kedua bersifat ekplisit untuk semua bahasa. Sedangkan untuk bagian terakhir adalah eksplisit untuk bahasa tingkat rendah, tetapi hampir semua bahasa tingkat atas seperti JavaScript juga bersifat implisit.

- -

Allocation in JavaScript

- -

Value initialization

- -

In order not to bother the programmer with allocations, JavaScript does it alongside with declaring values.

- -
var n = 123; // allocates memory for a number
-var s = "azerty"; // allocates memory for a string
-
-var o = {
-  a: 1,
-  b: null
-}; // allocates memory for an object and contained values
-
-// (like object) allocates memory for the array and
-// contained values
-var a = [1, null, "abra"];
-
-function f(a){
-  return a + 2;
-} // allocates a function (which is a callable object)
-
-// function expressions also allocate an object
-someElement.addEventListener('click', function(){
-  someElement.style.backgroundColor = 'blue';
-}, false);
-
- -

Allocation via function calls

- -

Some function calls result in object allocation.

- -
var d = new Date(); // allocates a Date object
-
-var e = document.createElement('div'); // allocates a DOM element
- -

Some methods allocate new values or objects:

- -
var s = "azerty";
-var s2 = s.substr(0, 3); // s2 is a new string
-// Since strings are immutable value,
-// JavaScript may decide to not allocate memory,
-// but just store the [0, 3] range.
-
-var a = ["ouais ouais", "nan nan"];
-var a2 = ["generation", "nan nan"];
-var a3 = a.concat(a2);
-// new array with 4 elements being
-// the concatenation of a and a2 elements
-
- -

Using values

- -

Using value basically means reading and writing in allocated memory. This can be done by reading or writing the value of a variable or an object property or even passing an argument to a function.

- -

Release when the memory is not needed anymore

- -

Most of memory management issues come at this phase. The hardest task here is to find when "the allocated memory is not needed any longer". It often requires for the developer to determine where in the program such piece of memory is not needed anymore and free it.

- -

High-level languages embed a piece of software called "garbage collector" whose job is to track memory allocation and use in order to find when a piece of allocated memory is not needed any longer in which case, it will automatically free it. This process is an approximation since the general problem of knowing whether some piece of memory is needed is undecidable (can't be solved by an algorithm).

- -

Garbage collection

- -

As stated above the general problem of automatically finding whether some memory "is not needed anymore" is undecidable. As a consequence, garbage collections implement a restriction of a solution to the general problem. This section will explain the necessary notions to understand the main garbage collection algorithms and their limitations.

- -

References

- -

The main notion garbage collection algorithms rely on is the notion of reference. Within the context of memory management, an object is said to reference another object if the former has an access to the latter (either implicitly or explicitly). For instance, a JavaScript object has a reference to its prototype (implicit reference) and to its properties values (explicit reference).

- -

In this context, the notion of "object" is extended to something broader than regular JavaScript objects and also contains function scopes (or the global lexical scope).

- -

Reference-counting garbage collection

- -

This is the most naive garbage collection algorithm. This algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object.

- -

Example

- -
var o = {
-  a: {
-    b:2
-  }
-};
-// 2 objects are created. One is referenced by the other as one of its properties.
-// The other is referenced by virtue of being assigned to the 'o' variable.
-// Obviously, none can be garbage-collected
-
-
-var o2 = o; // the 'o2' variable is the second thing that
-            // has a reference to the object
-o = 1;      // now, the object that was originally in 'o' has a unique reference
-            // embodied by the 'o2' variable
-
-var oa = o2.a; // reference to 'a' property of the object.
-               // This object has now 2 references: one as a property,
-               // the other as the 'oa' variable
-
-o2 = "yo"; // The object that was originally in 'o' has now zero
-           // references to it. It can be garbage-collected.
-           // However what was its 'a' property is still referenced by
-           // the 'oa' variable, so it cannot be freed
-
-oa = null; // what was the 'a' property of the object originally in o
-           // has zero references to it. It can be garbage collected.
-
- -

Limitation: cycles

- -

There is a limitation when it comes to cycles. In the following example two objects are created and reference one another – thus creating a cycle. They will not get out of the function scope after the function call, so they are effectively useless and could be freed. However, the reference-counting algorithm considers that since each of both object is referenced at least once and none can be garbage-collected.

- -
function f(){
-  var o = {};
-  var o2 = {};
-  o.a = o2; // o references o2
-  o2.a = o; // o2 references o
-
-  return "azerty";
-}
-
-f();
-
- -

Real-life example

- -

Internet Explorer 6 and 7 are known to have reference-counting garbage collectors for DOM objects. Cycles are a common mistake that can generate memory leaks:

- -
var div;
-window.onload = function(){
-  div = document.getElementById("myDivElement");
-  div.circularReference = div;
-  div.lotsOfData = new Array(10000).join("*");
-};
-
- -

In the above example, the DOM element "myDivElement" has a circular reference to itself in the "circularReference" property. If the property is not explicitly removed or nulled, a reference-counting garbage collector will always have at least one reference intact and will keep the DOM element in memory even if it was removed from the DOM tree. If the DOM element holds lots of data (illustrated in the above example with the "lotsOfData" property), the memory consumed by this data will never be released.

- -

Mark-and-sweep algorithm

- -

This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable".

- -

This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

- -

This algorithm is better than the previous one since "an object has zero reference" leads to this object being unreachable. The opposite is not true as we have seen with cycles.

- -

As of 2012, all modern browsers ship a mark-and-sweep garbage-collector. All improvements made in the field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its reduction of the definition of when "an object is not needed anymore".

- -

Cycles are not a problem anymore

- -

In the first above example, after the function call returns, the 2 objects are not referenced anymore by something reachable from the global object. Consequently, they will be found unreachable by the garbage collector.

- -

The same thing goes with the second example. Once the div and its handler are made unreachable from the roots, they can both be garbage-collected despite referencing each other.

- -

Limitation: objects need to be made explicitly unreachable

- -

Although this is marked as a limitation, it is one that is rarely reached in practice which is why no one usually cares that much about garbage collection.

- -

See also

- - diff --git a/files/id/web/javascript/reference/about/index.html b/files/id/web/javascript/reference/about/index.html deleted file mode 100644 index 02c6ef967c..0000000000 --- a/files/id/web/javascript/reference/about/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Mengenai Pustaka Ini -slug: Web/JavaScript/Reference/About -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/About ---- -

Apa yang perlu diketahui sebelumnya

- -

Pengalaman menggunakan bahasa pemrograman lainnya dapat menjadi manfaat, meskipun tidak menjadi prasyarat.

- -

JavaScript ditujukan untuk digunakan pada lingkup yang lebih besar, seperti peramban, script server-side, atau sejenisnya. Secara umum, pustaka ini tergantung pada platform tertentu, dan tidak ditujukan hanya untuk peramban.

- -

Untuk tujuan demo, pustakan ini menggunakan fungsi, println. Fungsi tersebut bukanlah bagian dari JavaScript. Namun ia dapat dipetakan terhadap implementasi spesifik pada platform tertentu.

- -

Misal, bila berjalan di peramban, maka fungsi di atas dapat implementasikan sebagai:

- -
-
function println(string) {
-  window.alert(string);
-}
-
- -

 

-
- -

Sejarah JavaScript

- -

Versi terbaru dari peramban berbasis Mozilla mendukung versi terbaru dari JavaScript. Tabel berikut menampilkan daftar dari versi JavaScript yang didukung oleh versi yang berbeda dari peramban berbasis Mozilla.

- -

Peramban yang tidak mendukung versi JavaScript setidaknya versi 1.5 adalah hal yang sangat langka untuk saat ini. JavaScript versi 1.5 sudah dipublikasikan sejak tahun 1999. Bila Anda tertarik untuk mempelajari sejarahnya, silahkan mengunjungi referensi yang terdapat di Wikipedia, ECMAScript.

- -

JavaScript/Browser support history

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
JavaScript (SpiderMonkey) versionMozilla releaseGecko version
JavaScript 1.5Navigator 6.0, Mozilla Application Suite, Firefox 1.0Gecko 0.6x-1.7
JavaScript 1.6Firefox 1.5Gecko 1.8
JavaScript 1.7Firefox 2Gecko 1.8.1
JavaScript 1.8Firefox 3Gecko 1.9
JavaScript 1.8.5Firefox 4Gecko 2.0
JavaScript 1.8.6Firefox 17Gecko 17
- -

Sumber informasi JavaScript

- -

Dokumentasi JavaScript dari fitur bahasa inti (murni ECMAScript, untuk sebagian besar) mencakup:

- - - -

Bila Anda masih baru terhadap JavaScript, mulailah dari pedoman. Bila kemudian Anda sudah merasa memiliki pemahaman yang lebih mendalam, Anda dapat memanfaatkan referensi.

diff --git a/files/id/web/javascript/reference/classes/constructor/index.html b/files/id/web/javascript/reference/classes/constructor/index.html deleted file mode 100644 index 8da1df9428..0000000000 --- a/files/id/web/javascript/reference/classes/constructor/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: constructor -slug: Web/JavaScript/Reference/Classes/constructor -translation_of: Web/JavaScript/Reference/Classes/constructor ---- -
{{jsSidebar("Classes")}}
- -

Metode dengan nama "constructor" adalah metode spesial untuk pembuatan dan penginisialisasian objek yang dibuat dengan kelas.

- -

sintaks

- -
constructor([arguments]) { ... }
- -

Deskripsi

- -

Hanya boleh ada satu metode spesial dengan nama "constructor" dalam sebuah kelas. {{jsxref("SyntaxError")}}  akan dilemparkan jika suatu kelas memiliki lebih dari satu metode konstruktor.

- -

Konstruktor dapat menggunakan kata kunci {{jsxref("Operators/super", "super")}} untuk memanggil konstruktor orang-tua.

- -

Jika metode konstruktor tidak didefinisikan dalam sebuah kelas, maka  kontruktor asali yang akan digunakan.

- -

Contoh

- -

Menggunakan metode constructor

- -

Potongan kode ini diambil dari contoh kelas (demostrasi langsung).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Di sini, akan memanggil konstruktor orang-tua dengan panjang
-    // diberikan untuk panjang dan tinggi Polygon
-    super(length, length);
-    // Catatan: di kelas turunan, super() harus dipanggil sebelum
-    // bisa menggunakan kata kunci 'this'. Meninggalkan pemanggilan ini di awal
-    // akan menyebabkan kesalahan referensi.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-
-  set area(value) {
-    this.area = value;
-  }
-}
- -

Konstruktor asali

- -

Jika metode konstruktor tidak didefinisikan dalam sebuah kelas, maka kontruktor asali yang akan digunakan. Untuk konstruktor asali untuk kelas dasar adalah:

- -
constructor() {}
-
- -

Konstruktor asali untuk kelas turunan adalah:

- -
constructor(...args) {
-  super(...args);
-}
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES6')}}Definisi awal
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas Peramban

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Default constructors{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Default constructors{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat Pula

- - diff --git a/files/id/web/javascript/reference/classes/extends/index.html b/files/id/web/javascript/reference/classes/extends/index.html deleted file mode 100644 index c6def454fe..0000000000 --- a/files/id/web/javascript/reference/classes/extends/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: extends -slug: Web/JavaScript/Reference/Classes/extends -tags: - - ECMAScript 2015 - - JavaScript - - Kelas -translation_of: Web/JavaScript/Reference/Classes/extends ---- -
{{jsSidebar("Classes")}}
- -

Kata kunci extends digunakan pada class declarations atau class expressions untuk membuat sebuah class yang merupakan turunan dari class lain.

- -
{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}
- - - -

Sintaks

- -
class ChildClass extends ParentClass { ... }
- -

Deskripsi

- -

Kata kunci extends dapat digunakan untuk subclass custom classes dan built-in objects.

- -

.prototype dari suatu ekstensi harus berupa sebuah {{jsxref("Object")}} atau {{jsxref("null")}}.

- -

Contoh

- -

Menggunakan extends

- -

Contoh pertama membuat sebuah class bernama Square dari kelas bernama Polygon. Contoh ini diambil dari live demo (source).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Disini, obyek dari Square memanggil konstruktor dari parent class dengan argumen lengths yang tersedia
-    // untuk width dan height pada Polygon
-    super(length, length);
-    // Catatan: Pada kelas turunan, super() harus dipanggil sebelum Anda
-    // dapat menggunakan 'this'. Pengabaian terhadap hal tersebut akan menyebabkan reference error.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-}
- -

Menggunakan extends dengan built-in objects

- -

Contoh berikut mewarisi built-in {{jsxref("Date")}} object. Contoh ini diambil dari live demo (source).

- -
class myDate extends Date {
-  constructor() {
-    super();
-  }
-
-  getFormattedDate() {
-    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-    return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
-  }
-}
- -

Extending (Pewarisan) null

- -

Extending/pewarisan dari {{jsxref("null")}} bekerja layaknya seperti normal class, dengan pengecualian prototype object tidak mewarisi dari {{jsxref("Object.prototype")}}.

- -
class nullExtends extends null {
-  constructor() {}
-}
-
-Object.getPrototypeOf(nullExtends); // Function.prototype
-Object.getPrototypeOf(nullExtends.prototype) // null
-
-new nullExtends(); //ReferenceError: this is not defined
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- - - -

{{Compat("javascript.classes.extends")}}

- -

Cek juga

- - diff --git a/files/id/web/javascript/reference/classes/index.html b/files/id/web/javascript/reference/classes/index.html deleted file mode 100644 index 3a8a71f562..0000000000 --- a/files/id/web/javascript/reference/classes/index.html +++ /dev/null @@ -1,383 +0,0 @@ ---- -title: Classes -slug: Web/JavaScript/Reference/Classes -tags: - - Classes - - Constructors - - ECMAScript6 - - Inheritance - - Intermediate - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Classes ---- -
{{JsSidebar("Classes")}}
- -

Kelas di JavaScript diperkenalkan pada ECMAScript 6 seperti pemanis dari prototype-based JavaScript yang sudah ada. Syntax dari kelas tidak menggunakan model object-oriented inheritance yang baru. JavaScript kelas menyediakan syntax yang lebih sederhana dan rapi untuk membuat object-object dan mengatasi / dealing dengan turunan / inheritance.

- -

Definisi kelas

- -

Kelas seperti "fungsi istimewa", dan seperti kamu bisa mendeklarasikan ekspresi fungsi (function expressions) dan deklarasi fungsi (function declarations), syntax kelas sendiri mempunyai dua komponen: ekspresi kelas (class expressions) dan deklarasi kelas (class declarations).

- -

Deklarasi Kelas

- -

Salah satu cara untuk mendefinisikan kelas adalah dengan menggunakan class declaration / deklarasi kelas. Untuk mendeklarasikan kelas, kamu bisa menggunakan kata kunci class sebagai contoh class "Polygon" di bawah ini.

- -
class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
- -

Hoisting

- -

Perbedaan penting antara deklarasi fungsi (function declarations) dan deklarasi kelas (class declarations) adalah deklarasi fungsi  {{Glossary("Hoisting", "hoisted")}} dan  deklarasi class tidak. Pertama-tama kamu harus mendeklarasikan kelas dan mengaksesnya, jika tidak maka kode seperti berikut akan menampilkan {{jsxref("ReferenceError")}}:

- -
var p = new Polygon(); // ReferenceError
-
-class Polygon {}
-
- -

Ekspresi Kelas

- -

Ekspresi kelas (class expression) adalah cara lain untuk mendefinisikan sebuah class. Class expression bisa bernama ataupun tidak. Nama yang diberikan berbentuk lokal berada di body class.

- -
// unnamed
-var Polygon = class {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
-// named
-var Polygon = class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
- -

Catatan: Ekspresi kelas (Class expressions) juga mempunyai masalah yang sama terkait hoisting seperti pada Deklarasi kelas (Class declarations).

- -

Tubuh Kelas (class body) and definisi metode

- -

Tubuh atau body sebuah kelas berada didalam kurung {}. Disitu kamu dapat mendefinisikan isi kelas seperti method atau konstruktor.

- -

Strict mode

- -

Body atau bagian badan dari kelas deklarasi dan kelas ekspresi di eksekusi pada strict mode.

- -

Konstruktor

- -

konstruktor adalah metode (method) khusus untuk membuat dan inisialisasi sebuah objek yang dibuat dengan  class. Hanya ada satu metode khusus dengan nama "konstruktor" di kelas. Sebuah {{jsxref("SyntaxError")}} akan tampil jika kelas berisi lebih dari satu method constructor.

- -

Sebuah konstruktor dapat digunakan keyword super untuk memanggil kostruktor dari kelas parent nya.

- -

Prototipe method

- -

Lihat juga definisi method

- -
class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-
-  get area() {
-    return this.calcArea();
-  }
-
-  calcArea() {
-    return this.height * this.width;
-  }
-}
-
-const square = new Polygon(10, 10);
-
-console.log(square.area);
- -

Metode Statis

- -

Kata kunci statis mendefinisikan metode statis untuk suatu kelas. Metode statis dipanggil tanpa membuat instance kelasnya dan tidak bisa dipanggil ketika kelas tersebut dipakai. Metode statis sering digunakan untuk membuat fungsi utilitas untuk suatu aplikasi.

- -
class Point {
-  constructor(x, y) {
-    this.x = x;
-    this.y = y;
-  }
-
-  static distance(a, b) {
-    const dx = a.x - b.x;
-    const dy = a.y - b.y;
-
-    return Math.sqrt(dx*dx + dy*dy);
-  }
-}
-
-const p1 = new Point(5, 5);
-const p2 = new Point(10, 10);
-
-console.log(Point.distance(p1, p2));
- -

Mem-binding this dengan prototipe dan metode statis

- -

Ketika metode statis atau prototipe dipanggil tanpa objek yang bernilai "this" (atau "this" sebagai boolean, string, angka, tidak terdefinisi atau null), maka nilai "this" akan ditentukan dalam fungsi yang digunakan. Autoboxing tidak akan berjalan. Hal tersebut juga berlaku ketika kita menulis kode dalam mode non-strict.laku akan sama bahkan jika kita menulis kode dalam mode tidak ketat.

- -
class Animal {
-  speak() {
-    return this;
-  }
-  static eat() {
-    return this;
-  }
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // undefined
-
-let eat = Animal.eat;
-eat(); // undefined
- -

Jika kita menulis kode diatas menggunakan fungsi tradisional berdasarkan kelas, maka autoboxing akan berjalan sesuai dengan nilai "this" pada fungsi yang dipanggil.

- -
function Animal() { }
-
-Animal.prototype.speak = function(){
-  return this;
-}
-
-Animal.eat = function() {
-  return this;
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // global object
-
-let eat = Animal.eat;
-eat(); // global object
-
- -

Sub kelas dengan extends

- -

extends digunakan pada deklarasi kelas atau kelas expresi untuk membuat suatu kelas sebagai turunan dari kelas lain.

- -
class Animal {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Jika terdapat constructor pada sub kelas saat ini, maka pertama dibutuhkan untuk memanggil super() sebelum menggunakan "this".

- -
Seseorang juga dapat mengextend "kelas" berbasis fungsi tradisional:
- -
function Animal (name) {
-  this.name = name;
-}
-
-Animal.prototype.speak = function () {
-  console.log(this.name + ' makes a noise.');
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Perhatikan bahwa kelas tidak dapat di extend pada objek reguler atau biasa (non-constructible) . Jika ingin mewarisi regurel object,  maka dapat menggunakan {{jsxref("Object.setPrototypeOf()")}}:

- -
var Animal = {
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-};
-
-class Dog {
-  constructor(name) {
-    this.name = name;
-  }
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-Object.setPrototypeOf(Dog.prototype, Animal);
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Species

- -

Kamu dapat mengembalikan objek {{jsxref("Array")}}  di kelas array yang diturunkan MyArray. Pola spesies memungkinkan Kamu overide konstruktor default.

- -

Contohnya, ketika menggunakan method seperti {{jsxref("Array.map", "map()")}} yang mana mengembalikan konstruktor default, kamu butuh method yang dapat mengembalikan objek parent Array, bukan dari objek MyArray. Simbol {{jsxref("Symbol.species")}} memungkinkan untuk melakukan:

- -
class MyArray extends Array {
-  // Overwrite species to the parent Array constructor
-  static get [Symbol.species]() { return Array; }
-}
-
-var a = new MyArray(1,2,3);
-var mapped = a.map(x => x * x);
-
-console.log(mapped instanceof MyArray); // false
-console.log(mapped instanceof Array);   // true
-
- -

Memanggil Kelas Super dengan keyword super

- -

Keyword super digunakan untuk memanggil fungsi pada objek parent nya.

- -
class Cat {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-}
-
-class Lion extends Cat {
-  speak() {
-    super.speak();
-    console.log(this.name + ' roars.');
-  }
-}
-
- -

Mix-ins

- -

Subkelas Abstrak or mix-ins adalah template untuk kelas. Kelas berbasis  ECMAScript hanya dapat memiliki satu superclass (Kelas super), jadi inheritence berganda dari kelas tool sebagai contohnya, itu tidak memungkinkan. Fungsionalitas harus disediakan oleh superclass.

- -

Sebuah fungsi dengan superclass sebagai inputanya dan sukelas as input and a subclass extend superclass sebagai output dapat mengimplemtasikan pada  ECMAScript sebagai berikut:

- -
var calculatorMixin = Base => class extends Base {
-  calc() { }
-};
-
-var randomizerMixin = Base => class extends Base {
-  randomize() { }
-};
-
- -

A class that uses these mix-ins can then be written like this:

- -
class Foo { }
-class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
- -

Kompatibilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]
- {{CompatChrome(49.0)}}
{{CompatGeckoDesktop(45)}}13{{CompatNo}}{{CompatNo}}{{CompatSafari(9.0)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}9{{CompatChrome(42.0)}}[1]
- {{CompatChrome(49.0)}}
-
- -

[1] Requires strict mode. Non-strict mode support is behind the flag "Enable Experimental JavaScript", disabled by default.

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html b/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html deleted file mode 100644 index 4fab8e8ca2..0000000000 --- a/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: X.prototype.y called on incompatible type -slug: Web/JavaScript/Reference/Errors/Called_on_incompatible_type -tags: - - Error - - JavaScript - - TypeError -translation_of: Web/JavaScript/Reference/Errors/Called_on_incompatible_type ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
TypeError: 'this' is not a Set object (EdgE)
-TypeError: Function.prototype.toString called on incompatible object (Firefox)
-TypeError: Function.prototype.bind called on incompatible target (Firefox)
-TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome)
-TypeError: Bind must be called on a function (Chrome)
-
- -

Tipe error

- -

{{jsxref("TypeError")}}

- -

Apa yang salah?

- -

Ketika error ini dilempar, suatu fungsi (dari objek yang diberikan), dipanggil dengan this tidak berkorespondensi ke tipe yang diharapkan fungsi tersebut.

- -

Isu ini bisa terbit ketika menggunakan metode {{jsxref("Function.prototype.call()")}} atau {{jsxref("Function.prototype.apply()")}}, dan menyediakan argumen this yang tak punya tipe yang diharapkan.

- -

Isu ini juga bisa terjadi ketika menyediakan fungsi yang disimpan sebagai properti suatu objek sebagai argumen fungsi lain. Dalam hal ini, objek yang menyimpan fungsi tersebut takkan menjadi target this target dari fungsi itu ketika dipanggil oleh fungsi lain. Untuk mengatasi isu ini, kamu harus menyediakan lambda yang membuat panggilan, ataupun menggunakan fungsi {{jsxref("Function.prototype.bind()")}} untuk memaksa argumen this ke objek yang diharapkan.

- -

Contoh

- -

Kasus tak valid

- -
var mySet = new Set;
-['bar', 'baz'].forEach(mySet.add);
-// mySet.add adalah fungsi, tapi "mySet" tidak dikaptur sebagai this.
-
-var myFun = function () {
-  console.log(this);
-};
-['bar', 'baz'].forEach(myFun.bind);
-// myFun.bind adalah fungsi, tapi "myFun" tidak dikaptur sebagai this.
-
-
- -

Kasus valid

- -
var mySet = new Set;
-['bar', 'baz'].forEach(mySet.add.bind(mySet));
-// Ini berjalan karena mengikat "mySet" sebagai this.
-
-var myFun = function () {
-  console.log(this);
-};
-['bar', 'baz'].forEach(x => myFun.bind(x));
-// Ini berjalan menggunakan fungsi "bind". Ia membuat lambda yang meneruskan argumen.
-
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/index.html b/files/id/web/javascript/reference/errors/index.html deleted file mode 100644 index 68e7cce3df..0000000000 --- a/files/id/web/javascript/reference/errors/index.html +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Referensi error JavaScript -slug: Web/JavaScript/Reference/Errors -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/Errors ---- -

{{jsSidebar("Errors")}}

- -

Error, error dimana - mana.

- -

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

diff --git a/files/id/web/javascript/reference/errors/invalid_array_length/index.html b/files/id/web/javascript/reference/errors/invalid_array_length/index.html deleted file mode 100644 index 3b7fd4e78e..0000000000 --- a/files/id/web/javascript/reference/errors/invalid_array_length/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: 'RangeError: invalid array length' -slug: Web/JavaScript/Reference/Errors/Invalid_array_length -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
RangeError: Array length must be a finite positive integer (Edge)
-RangeError: invalid array length (Firefox)
-RangeError: Invalid array length (Chrome)
-RangeError: Invalid array buffer length (Chrome)
-
- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

Panjang array tak valid bisa muncul di situasi berikut:

- - - -

Kenapa panjang Array dan ArrayBuffer dibatasi? Properti length dari Array atau ArrayBuffer diwakili dengan satu unsigned 32-bit integer, yang hanya menyimpan nilai dalam kisaran dari 0 hingga 232-1.

- -

Jika kamu membuat satu Array, menggunakan constructor, kamu mungkin mau memakai notasi literal saja, karena argumen pertama diinterpretasi sebagai panjang Array.

- -

Sebaliknya, kamu mungkin mau mengelam panjangnya sebelum mengeset properti panjangnya, atau memakainya sebagai argumen konstructor.

- -

Contoh

- -

Kasus tak valid

- -
new Array(Math.pow(2, 40))
-new Array(-1)
-new ArrayBuffer(Math.pow(2, 32))
-new ArrayBuffer(-1)
-
-let a = [];
-a.length = a.length - 1;         // set -1 to the length property
-
-let b = new Array(Math.pow(2, 32) - 1);
-b.length = b.length + 1;         // set 2^32 to the length property
-
- -

Kasus valid

- -
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
-[ -1 ]                                  // [ -1 ]
-new ArrayBuffer(Math.pow(2, 32) - 1)
-new ArrayBuffer(0)
-
-let a = [];
-a.length = Math.max(0, a.length - 1);
-
-let b = new Array(Math.pow(2, 32) - 1);
-b.length = Math.min(0xffffffff, b.length + 1);
-
-// 0xffffffff is the hexadecimal notation for 2^32 - 1
-// which can also be written as (-1 >>> 0)
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html deleted file mode 100644 index 32be54e5ce..0000000000 --- a/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: 'SyntaxError: missing ; before statement' -slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement -translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
SyntaxError: Expected ';' (Edge)
-SyntaxError: missing ; before statement (Firefox)
-
- -

Tipe error

- -

{{jsxref("SyntaxError")}}.

- -

Apa yang Salah?

- -

Ada titik koma (;) yang hilang di suatu tempat. JavaScript statements harus diakhiri dengan semicolon. Beberapa dari mereka dipengaruhi oleh automatic semicolon insertion (ASI), tetapi dalam hal ini anda perlu memberikan titik koma, sehingga JavaScript dapat mem-parse kode sumber dengan benar.

- -

Namun, seringkali, kesalahan ini hanya merupakan konsekuensi dari kesalahan lain, seperti tidak menempatkan string dengan benar, atau menggunakan var secara salah. Ada mungkin juga memiliki terlalu banyak tanda kurung di suatu tempat. Hati-hati memeriksa sintaks ketika kesalahan ini dilemparkan.

- -

Contoh

- -

Unescaped strings

- -

Kesalahan ini dapat terjadi dengan mudah ketika tidak melepaskan string dengan benar dan engine JavaScript is expecting the end of your string already. Sebagai contoh:

- -
var foo = 'Tom's bar';
-// SyntaxError: missing ; before statement
- -

Anda dapat menggunakan double quotes, atau menggunakan tanda kutip dengan menambahkan backslash

- -
var foo = "Tom's bar";
-var foo = 'Tom\'s bar';
-
- -

Declaring properties with var

- -

Anda tidak dapat mendeklarasikan property dari sebuah objek atau larik(array) dengan deklarasi var.

- -
var obj = {};
-var obj.foo = 'hi'; // SyntaxError missing ; before statement
-
-var array = [];
-var array[0] = 'there'; // SyntaxError missing ; before statement
-
- -

Sebagai gantinya, hapus kata kunci var:

- -
var obj = {};
-obj.foo = 'hi';
-
-var array = [];
-array[0] = 'there';
-
- -

Kata kunci yang buruk

- -

Jika ada berasal dari bahasa pemrograman yang lain, itu juga umum untuk menggunakan kata kunci yang tidak berarti sama atau tidak memiliki arti sama sekali di JavaScript:

- -
def print(info){
-  console.log(info);
-}; // SyntaxError missing ; before statement
- -

Sebagai gantinya, gunakan function daripada menggunakan kata kunci def:

- -
function print(info){
-  console.log(info);
-};
- -

See also

- - diff --git a/files/id/web/javascript/reference/errors/negative_repetition_count/index.html b/files/id/web/javascript/reference/errors/negative_repetition_count/index.html deleted file mode 100644 index 0ea4bec83a..0000000000 --- a/files/id/web/javascript/reference/errors/negative_repetition_count/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: 'RangeError: repeat count must be non-negative' -slug: Web/JavaScript/Reference/Errors/Negative_repetition_count -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Negative_repetition_count ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
RangeError: argument out of range
-RangeError: repeat count must be non-negative (Firefox)
-RangeError: Invalid count value (Chrome)
-
- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

Metode {{jsxref("String.prototype.repeat()")}} telah digunakan. Ia punya parameter count mengindikasikan jumlah pengulangan string. Ia harus bernilai antara 0 dan kurang dari positif {{jsxref("Infinity")}} dan tidak boleh angka negatif. Kisarannya nilai yang diperbolehkan bisa dijelaskan seperti ini: [0, +∞).

- -

Contoh

- -

Kasus tak valid

- -
'abc'.repeat(-1); // RangeError 
- -

Kasus valid

- -
'abc'.repeat(0);    // ''
-'abc'.repeat(1);    // 'abc'
-'abc'.repeat(2);    // 'abcabc'
-'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/not_a_codepoint/index.html b/files/id/web/javascript/reference/errors/not_a_codepoint/index.html deleted file mode 100644 index d3d8b2f934..0000000000 --- a/files/id/web/javascript/reference/errors/not_a_codepoint/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: 'RangeError: argument is not a valid code point' -slug: Web/JavaScript/Reference/Errors/Not_a_codepoint -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Not_a_codepoint ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
RangeError: Invalid code point {0} (Edge)
-RangeError: {0} is not a valid code point (Firefox)
-RangeError: Invalid code point {0} (Chrome)
-
- -

 

- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

{{jsxref("String.fromCodePoint()")}} throws this error when passed {{jsxref("NaN")}} values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111).

- -

Satu poin kode ialah satu nilai dalam codespace Unicode; yaitu, kisaran integer dari 0 hingga 0x10FFFF.

- -

Contoh

- -

Kasus tak nvalid

- -
String.fromCodePoint('_');      // RangeError
-String.fromCodePoint(Infinity); // RangeError
-String.fromCodePoint(-1);       // RangeError
-String.fromCodePoint(3.14);     // RangeError
-String.fromCodePoint(3e-2);     // RangeError
-String.fromCodePoint(NaN);      // RangeError
- -

Kasus valid

- -
String.fromCodePoint(42);       // "*"
-String.fromCodePoint(65, 90);   // "AZ"
-String.fromCodePoint(0x404);    // "\u0404"
-String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
-String.fromCodePoint(194564);   // "\uD87E\uDC04"
-String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/not_defined/index.html b/files/id/web/javascript/reference/errors/not_defined/index.html deleted file mode 100644 index d0dc93a0c6..0000000000 --- a/files/id/web/javascript/reference/errors/not_defined/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: 'ReferenceError: "x" is not defined' -slug: Web/JavaScript/Reference/Errors/Not_defined -translation_of: Web/JavaScript/Reference/Errors/Not_defined ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
ReferenceError: "x" is not defined
-
- -

Type Error

- -

{{jsxref("ReferenceError")}}.

- -

Mengapa salah?

- -

Tidak ditemukannya referensi variabel dimanapun. Variabel ini perlu dideklarasikan, atau anda pastikan lagi bahwa ada di dalam script atau {{Glossary("scope")}} anda.

- -
-

Note: Ketika memanggil sebuah library (seperti jQuery), pastikan memanggilnya terlebih dahulu tanda "$" sebelum mengakses variabel library. Gunakan tag {{HTMLElement("script")}} untuk memanggil library sebelum menggunakannya pada kode anda.

-
- -

Contoh

- -

Variable tidak dideklarasikan

- -
foo.substring(1); // ReferenceError: foo is not defined
-
- -

Variabel "foo" tidak ditemukan dimanapun. Variabel tersebut diperlukan oleh beberapa string, agar metode {{jsxref("String.prototype.substring()")}} dapat bekerja.

- -
var foo = 'bar';
-foo.substring(1); // "ar"
- -

Ruang lingkup salah

- -

Sebuah variabel harus tersedia dalam kontek eksekusi saat ini . Variabel yang berada di dalam sebuah fungsi tidak dapat diakses dari luar fungsi, sebab sebuah variabel mepunyai batasan pada cakupan wilayah sebuah fungsi

- -
function numbers() {
-  var num1 = 2,
-      num2 = 3;
-  return num1 + num2;
-}
-
-console.log(num1); // ReferenceError num1 is not defined.
- -

Dengan demikian sebuah fungsi dapat mengakses semua variabel dan fungsi lainnya yang didefinisikan di dalam cakupan dimana ia didefinisikan. Dengan kata lain, sebiah fungsi yang didefinisikan di cakupan global dapat mengakses semua variabel yang didefinisian secara global pula.

- -
var num1 = 2,
-    num2 = 3;
-
-function numbers() {
-  return num1 + num2;
-}
-
-console.log(numbers()); // 5
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/property_access_denied/index.html b/files/id/web/javascript/reference/errors/property_access_denied/index.html deleted file mode 100644 index 6cbece3868..0000000000 --- a/files/id/web/javascript/reference/errors/property_access_denied/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: 'Error: Permission denied to access property "x"' -slug: Web/JavaScript/Reference/Errors/Property_access_denied -tags: - - Error - - Errors - - JavaScript - - Keamanan -translation_of: Web/JavaScript/Reference/Errors/Property_access_denied ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
Error: Permission denied to access property "x"
-
- -

Tipe error

- -

{{jsxref("Error")}}.

- -

Apa kesalahannya?

- -

Ada usaha pengaksesan objeck yang kamu belum punya ijinnya. Sepertinya elemen {{HTMLElement("iframe")}} diload dari domain berbeda yang kebijakan same-origin policynya kamu langgar.

- -

Contoh

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe>
-    <script>
-      onload = function() {
-        console.log(frames[0].document);
-        // Error: Permission denied to access property "document"
-      }
-    </script>
-  </head>
-  <body></body>
-</html>
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/too_much_recursion/index.html b/files/id/web/javascript/reference/errors/too_much_recursion/index.html deleted file mode 100644 index 4c35bcfc83..0000000000 --- a/files/id/web/javascript/reference/errors/too_much_recursion/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: 'InternalError: too much recursion' -slug: Web/JavaScript/Reference/Errors/Too_much_recursion -tags: - - Errors - - InternalError - - JavaScript -translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
Error: Out of stack space (Edge)
-InternalError: too much recursion (Firefox)
-RangeError: Maximum call stack size exceeded (Chrome)
-
- -

Tipe error

- -

{{jsxref("InternalError")}}.

- -

Apa yang salah?

- -

Fungsi yang memanggil dirinya sendiri disebut fungsi rekursif. Sekali satu kondisi telah ketemu, fungsi itu berhenti memanggil dirinya. Ini disebut base case.

- -

Dalam beberapa cara, rekursi analog dengan loop. Keduanya mengeksekusi kode yang sama berulang kali, dan keduanya membutuhkan satu kondisi (untuk mencegah loop tak-terbatas, atau lebih tepatnya, rekursi tak-terbatas dalam hal ini). Ketika panggilan fungsi terlalu banyak, atau tak ada base case dalam fungsi, JavaScript akan melempar error ini.

- -

Contoh

- -

Fungsi rekursif ini berjalan 10 kali, per kondisi exit.

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" is the exit condition
-    return;
-  // do stuff
-  loop(x + 1); // the recursive call
-}
-loop(0);
- -

Mengeset kondisi ini ke nilai extrem sangat tinggi, tak akan jalan:

- -
function loop(x) {
-  if (x >= 1000000000000)
-    return;
-  // do stuff
-  loop(x + 1);
-}
-loop(0);
-
-// InternalError: too much recursion
- -

Fungsi rekursif ini tak punya base case. Jika tak kondisi exit, function akan memanggil dirinya sendiri terus-terusan.

- -
function loop(x) {
- // The base case is missing
-
-loop(x + 1); // Recursive call
-}
-
-loop(0);
-
-// InternalError: too much recursion
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/functions/index.html b/files/id/web/javascript/reference/functions/index.html deleted file mode 100644 index adb0d13f05..0000000000 --- a/files/id/web/javascript/reference/functions/index.html +++ /dev/null @@ -1,596 +0,0 @@ ---- -title: Functions -slug: Web/JavaScript/Reference/Functions -tags: - - Constructor - - Function - - Functions - - JavaScript - - NeedsTranslation - - Parameter - - TopicStub - - parameters -translation_of: Web/JavaScript/Reference/Functions ---- -
{{jsSidebar("Functions")}}
- -

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

- -

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

- -

For more examples and explanations, see also the JavaScript guide about functions.

- -

Description

- -

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

- -

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

- -

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

- -
/* Declare the function 'myFunc' */
-function myFunc(theObject) {
-  theObject.brand = "Toyota";
-}
-
-/*
- * Declare variable 'mycar';
- * create and initialize a new Object;
- * assign reference to it to 'mycar'
- */
-var mycar = {
-  brand: "Honda",
-  model: "Accord",
-  year: 1998
-};
-
-/* Logs 'Honda' */
-console.log(mycar.brand);
-
-/* Pass object reference to the function */
-myFunc(mycar);
-
-/*
- * Logs 'Toyota' as the value of the 'brand' property
- * of the object, as changed to by the function.
- */
-console.log(mycar.brand);
-
- -

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

- -

Defining functions

- -

There are several ways to define functions:

- -

The function declaration (function statement)

- -

There is a special syntax for declaring functions (see function statement for details):

- -
function name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The function expression (function expression)

- -

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

- -
function [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function.
-
statements
-
The statements comprising the body of the function.
-
- -

Here is an example of an anonymous function expression (the name is not used):

- -
var myFunction = function() {
-    statements
-}
- -

It is also possible to provide a name inside the definition in order to create a named function expression:

- -
var myFunction = function namedFunction(){
-    statements
-}
-
- -

One of the benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

- -

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

- -

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

- -
(function() {
-    statements
-})();
- -

IIFE are function expressions that are invoked as soon as the function is declared.

- -

The generator function declaration (function* statement)

- -

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

- -
function* name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The generator function expression (function* expression)

- -

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

- -
function* [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function.
-
statements
-
The statements comprising the body of the function.
-
- -

The arrow function expression (=>)

- -

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

- -
([param[, param]]) => {
-   statements
-}
-
-param => expression
-
- -
-
param
-
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
-
statements or expression
-
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
-
- -

The Function constructor

- -
-

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

- -
new Function (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function body.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

The GeneratorFunction constructor

- -
-

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

-
- -
-

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

- -
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Function parameters

- -

Default parameters

- -

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

- -

Rest parameters

- -

The rest parameter syntax allows representing an indefinite number of arguments as an array. For more details, see rest parameters.

- -

The arguments object

- -

You can refer to a function's arguments within the function by using the arguments object. See arguments.

- - - -

Defining method functions

- -

Getter and setter functions

- -

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -
-
get
-
-

Binds an object property to a function that will be called when that property is looked up.

-
-
set
-
Binds an object property to a function to be called when there is an attempt to set that property.
-
- -

Method definition syntax

- -

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

- -
var obj = {
-  foo() {},
-  bar() {}
-};
- -

Constructor vs. declaration vs. expression

- -

Compare the following:

- -

A function defined with the Function constructor assigned to the variable multiply:

- -
var multiply = new Function('x', 'y', 'return x * y');
- -

A function declaration of a function named multiply:

- -
function multiply(x, y) {
-   return x * y;
-} // there is no semicolon here
-
- -

A function expression of an anonymous function assigned to the variable multiply:

- -
var multiply = function(x, y) {
-   return x * y;
-};
-
- -

A function expression of a function named func_name assigned to the variable multiply:

- -
var multiply = function func_name(x, y) {
-   return x * y;
-};
-
- -

Differences

- -

All do approximately the same thing, with a few subtle differences:

- -

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

- -
var y = function x() {};
-alert(x); // throws an error
-
- -

The function name also appears when the function is serialized via Function's toString method.

- -

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

- -

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

- -

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

- -
function anonymous() {
-}
-
- -

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

- -
var foo = new Function("alert(anonymous);");
-foo();
-
- -

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

- -
foo(); // alerts FOO!
-function foo() {
-   alert('FOO!');
-}
-
- -

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

- -
/*
- * Declare and initialize a variable 'p' (global)
- * and a function 'myFunc' (to change the scope) inside which
- * declare a varible with same name 'p' (current) and
- * define three functions using three different ways:-
- *     1. function declaration
- *     2. function expression
- *     3. function constructor
- * each of which will log 'p'
- */
-var p = 5;
-function myFunc() {
-    var p = 9;
-
-    function decl() {
-        console.log(p);
-    }
-    var expr = function() {
-        console.log(p);
-    };
-    var cons = new Function('\tconsole.log(p);');
-
-    decl();
-    expr();
-    cons();
-}
-myFunc();
-
-/*
- * Logs:-
- * 9  - for 'decl' by function declaration (current scope)
- * 9  - for 'expr' by function expression (current scope)
- * 5  - for 'cons' by Function constructor (global scope)
- */
-
- -

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

- -

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

- -
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
-foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
- -

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

- - - -
var x = 0;               // source element
-if (x === 0) {           // source element
-   x = 10;               // not a source element
-   function boo() {}     // not a source element
-}
-function foo() {         // source element
-   var y = 20;           // source element
-   function bar() {}     // source element
-   while (y === 10) {    // source element
-      function blah() {} // not a source element
-      y++;               // not a source element
-   }
-}
-
- -

Examples

- -
// function declaration
-function foo() {}
-
-// function expression
-(function bar() {})
-
-// function expression
-x = function hello() {}
-
-
-if (x) {
-   // function expression
-   function world() {}
-}
-
-
-// function declaration
-function a() {
-   // function declaration
-   function b() {}
-   if (0) {
-      // function expression
-      function c() {}
-   }
-}
-
- -

Block-level functions

- -

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -
'use strict';
-
-function f() {
-  return 1;
-}
-
-{
-  function f() {
-    return 2;
-  }
-}
-
-f() === 1; // true
-
-// f() === 2 in non-strict mode
-
- -

Block-level functions in non-strict code

- -

In a word: Don't.

- -

In non-strict code, function declarations inside blocks behave strangely. For example:

- -
if (shouldDefineZero) {
-   function zero() {     // DANGER: compatibility risk
-      console.log("This is zero.");
-   }
-}
-
- -

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

- -

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

- -

A safer way to define functions conditionally is to assign a function expression to a variable:

- -
var zero;
-if (shouldDefineZero) {
-   zero = function() {
-      console.log("This is zero.");
-   };
-}
-
- -

Examples

- -

Returning a formatted number

- -

The following function returns a string containing the formatted representation of a number padded with leading zeros.

- -
// This function returns a string padded with leading zeros
-function padZeros(num, totalLen) {
-   var numStr = num.toString();             // Initialize return value as string
-   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
-   for (var i = 1; i <= numZeros; i++) {
-      numStr = "0" + numStr;
-   }
-   return numStr;
-}
-
- -

The following statements call the padZeros function.

- -
var result;
-result = padZeros(42,4); // returns "0042"
-result = padZeros(42,2); // returns "42"
-result = padZeros(5,4);  // returns "0005"
-
- -

Determining whether a function exists

- -

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise, some other action is taken.

- -
 if ('function' === typeof window.noFunc) {
-   // use noFunc()
- } else {
-   // do something else
- }
-
- -

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.functions")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/array/concat/index.html b/files/id/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index c6a25609db..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: Array.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -tags: - - Array -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -
{{JSRef}}
- -

Method concat() mengembalikan sebuah array baru yang terdiri dari array yang dipanggil kemudian digabung dengan array dan/atau nilai yang ditambahkan pada argumen.

- -

Syntax

- -
var array_baru = array_lama.concat(value1[, value2[, ...[, valueN]]])
- -

Parameter

- -
-
valueN
-
Array dan/atau nilai untuk digabung menjadi array baru. Untuk detailnya lihat deskripsi dibawah.
-
- -

Deskripsi

- -

concat menciptakan array baru yang terdiri dari unsur - unsur dalam object yang disebut, berdasarkan urutannya, setiap argumen, elemen dari argumen tersebut(Jika argumen adalah array) atau argumennya sendiri (jika argumennya bukan array).

- -

concat tidak mengubah this atau beberapa array yang tersedia sebagai argumen melainkan mengembalikan shallow copy yang berisi salinan dari elemen yang sama digabung dengan array yang asli. Elemen dari array asli disalin ke array baru sebagai berikut:

- - - -
-

Catatan: Concatenating array/nilai akan membiarkan aslinya tidak tersentuh. Selanjutnya, setiap operasi pada array baru tidak akan mempengaruhi array yang asli, begitupun sebaliknya.

-
- -

Contoh

- -

Menggabungkan dua Array

- -

Berikut kode untuk menggabunggkan dua array:

- -
var huruf = ['a', 'b', 'c'],
-    angka = [1, 2, 3];
-
-var hurufAngka = huruf.concat(angka);
-
-console.log(hurufAngka); // Hasil: ['a', 'b', 'c', 1, 2, 3]
-
- -

Menggabungkan tiga array

- -

Berikut kode untuk mengabungkan tiga array:

- -
var angka1 = [1, 2, 3],
-    angka2 = [4, 5, 6],
-    angka3 = [7, 8, 9];
-
-var angkaBaru = angka1.concat(angka2, angka3);
-
-console.log(angkaBaru); // Hasil: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
- -

Menggabungkan nilai ke sebuah array

- -

Berikut kode untuk menggabungkan tiga nilai ke sebuah array :

- -
var huruf = ['a', 'b', 'c'];
-
-var hurufAngka = huruf.concat(1, [2, 3]);
-
-console.log(hurufAngka);
-// Hasil: ['a', 'b', 'c', 1, 2, 3]
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/filter/index.html b/files/id/web/javascript/reference/global_objects/array/filter/index.html deleted file mode 100644 index 5c23313268..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/filter/index.html +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Array.prototype.filter() -slug: Web/JavaScript/Reference/Global_Objects/Array/filter -tags: - - Array - - ECMAScript 5 - - JavaScript - - Metode - - Referensi - - polyfill - - purwarupa -translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter ---- -
{{JSRef}}
- -

Fungsi filter() membuat array baru berisi elemen yang lolos pengecekan di dalam fungsi anonim yang dikirim sebagai parameter.

- -
var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
-
-var longWords = words.filter(function(word){
-  return word.length > 6;
-});
-
-// Filtered array longWords is ["exuberant", "destruction", "present"]
-
- -

Versi ES6

- -
const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
-
-let longWords = words.filter(word => word.length > 6);
-
-// Filtered array longWords is ["exuberant", "destruction", "present"]
-
- -

Sintaksis

- -
var newArray = arr.filter(callback[, thisArg])
- -

Parameter-parameter

- -
-
callback
-
Fungsi berupa tes untuk mengecek elemen yang ada di dalam array. Kembalikan nilai true untuk meloloskan element, false untuk tidak lolos, dan dapat memiliki tiga argumen:
-
-
-
element
-
Elemen saat ini yang sedang diproses.
-
index
-
Nilai indeks (posisi) dari elemen yang sedang diproses.
-
array
-
Array yang memanggil fungsi filter.
-
-
-
thisArg {{Optional_inline}}
-
Opsional. Objek yang akan digunakan sebagai this saat mengeksekusi callback.
-
- -

Nilai balikan

- -

Array baru yang berisi elemen lolos pengecekan.

- -

Deskripsi

- -

filter() akan memanggil fungsi callback sekali untuk tiap elemen di dalam array, dan membuat array baru dari semua nilai yang dianggap true dari hasil yang dikembalikan callbackcallback hanya dipanggil untuk indeks dari array yang berisi sebuah nilai; fungsi tidak akan dipanggil untuk indeks yang telah dihapus atau belum diisi nilai tertentu. Elemen array yang tidak lolos tes callback akan dilewati dan tidak dimasukkan ke dalam array baru.

- -

callback dapat dipanggil dengan tiga argumen:

- -
    -
  1. nilai dari elemen
  2. -
  3. indeks dari elemen
  4. -
  5. objek array yang diproses
  6. -
- -

Jika parameter thisArg tersedia juga saat memanggil filter, itu akan digunakan sebagai nilai this di dalam callback.  Jika tidak disediakan, maka undefined yang digunakan sebagai nilai this. Nilai this yang dapat digunakan dalam callback ditentukan dari aturan umum penentuan this dalam fungsi.

- -

filter() tidak mengubah array yang memanggil fungsi ini.

- -

Kumpulan elemen yang akan diproses oleh filter() ditentukan sebelum pemanggilan pertama callback. Elemen yang ditambahkan ke array setelah pemanggilanfilter() dimulai tidak akan diproses oleh callback. Jika elemen yang sudah ada dalam array berubah, atau dihapus, nilai yang digunakan dalam callback adalah nilai pada saat filter() menggunakannya; elemen yang dihapus tidak akan diproses.

- -

Contoh

- -

Menyaring semua nilai kecil

- -

Contoh berikut ini menggunakan filter() untuk membuat array yang menyaring semua nilai di bawah 10.

- -
function isBigEnough(value) {
-  return value >= 10;
-}
-
-var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
-// filtered is [12, 130, 44]
-
- -

Menyaring entri invalid dari JSON

- -

Contoh berikut ini menggunakan filter() untuk membuat json tersaring berisi semua elemen id berupa angka bukan nol.

- -
var arr = [
-  { id: 15 },
-  { id: -1 },
-  { id: 0 },
-  { id: 3 },
-  { id: 12.2 },
-  { },
-  { id: null },
-  { id: NaN },
-  { id: 'undefined' }
-];
-
-var invalidEntries = 0;
-
-function isNumber(obj) {
-  return obj!== undefined && typeof(obj) === 'number' && !isNaN(obj);
-}
-
-function filterByID(item) {
-  if (isNumber(item.id)) {
-    return true;
-  }
-  invalidEntries++;
-  return false;
-}
-
-var arrByID = arr.filter(filterByID);
-
-console.log('Filtered Array\n', arrByID);
-// Filtered Array
-// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]
-
-console.log('Number of Invalid Entries = ', invalidEntries);
-// Number of Invalid Entries = 4
-
- -

Pencarian dalam array

- -

Contoh berikut menggunakan filter() untuk menyaring isi array berdasarkan kriteria pencarian

- -
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
-
-/**
- * Array filters items based on search criteria (query)
- */
-function filterItems(query) {
-  return fruits.filter(function(el) {
-      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
-  })
-}
-
-console.log(filterItems('ap')); // ['apple', 'grapes']
-console.log(filterItems('an')); // ['banana', 'mango', 'orange']
- -

Implementasi ES2015

- -
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
-
-/**
- * Array filters items based on search criteria (query)
- */
-const filterItems = (query) => {
-  return fruits.filter((el) =>
-    el.toLowerCase().indexOf(query.toLowerCase()) > -1
-  );
-}
-
-console.log(filterItems('ap')); // ['apple', 'grapes']
-console.log(filterItems('an')); // ['banana', 'mango', 'orange']
-
-
- -

Polyfill

- -

filter() ditambahkan ke standar ECMA-262 baru pada edisi ke-5; sehingga fungsi ini mungkin tidak terdapat pada semua implementasi standar. Anda dapat mengatasi hal ini dengan menambahkan kode berikut pada awalan skrip Anda, memungkinkan penggunaan filter() di implementasi ECMA-262 yang belum mendukung. Algoritma ini persis sepadan dengan yang dispesifikasikan dalam ECMA-262, edisi ke-5, dengan asumsi fn.call dievaluasi ke nilai asli dari {{jsxref("Function.prototype.bind()")}}, dan {{jsxref("Array.prototype.push()")}} memiliki nilai aslinya.

- -
if (!Array.prototype.filter)
-  Array.prototype.filter = function(func, thisArg) {
-    'use strict';
-    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
-        throw new TypeError();
-
-    var len = this.length >>> 0,
-        res = new Array(len), // preallocate array
-        t = this, c = 0, i = -1;
-    if (thisArg === undefined)
-      while (++i !== len)
-        // checks to see if the key was set
-        if (i in this)
-          if (func(t[i], i, t))
-            res[c++] = t[i];
-    else
-      while (++i !== len)
-        // checks to see if the key was set
-        if (i in this)
-          if (func.call(thisArg, t[i], i, t))
-            res[c++] = t[i];
-
-    res.length = c; // shrink down array to proper size
-    return res;
-  };
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -
- - -

{{Compat("javascript.builtins.Array.filter")}}

-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/from/index.html b/files/id/web/javascript/reference/global_objects/array/from/index.html deleted file mode 100644 index 7845da9755..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/from/index.html +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Array.from() -slug: Web/JavaScript/Reference/Global_Objects/Array/from -translation_of: Web/JavaScript/Reference/Global_Objects/Array/from ---- -
{{JSRef}}
- -

Method Array.from() membuat sebuah instansi Array dari sebuah array-like atau objek iterable.

- -

Di ES6, sintaks class memungkinkan untuk subclassing diantaranya built-in dan user defined classes; hasilnya , method statik class-side seperti Array.from  "diwariskan" oleh subclasses dari Array dan membuat instansi baru dari subclass, bukan Array.

- -

Sintaks

- -
Array.from(arrayLike[, mapFn[, thisArg]])
-
- -

Parameter

- -
-
arrayLike
-
 Array-like atau objek iterable untuk diubah menjadi array.
-
mapFn
-
Opsional. Fungsi Map untuk memanggil setiap elemen array.
-
thisArg
-
Opsional. Nilai untuk digunakan this ketika mengeksekusi mapFn.
-
- -

Deskripsi

- -

Array.from() memungkinkan anda membuat Arrays dari:

- - - -

Array.from() memiliki parameter opsional mapFn, yang memungkinkan anda untuk mengeksekusi fungsi {{jsxref("Array.prototype.map", "map")}} pada setiap elemen array (atau objek subclass) yang akan dibuat. Jelasnya, Array.from(obj, mapFn, thisArg) sama dengan Array.from(obj).map(mapFn, thisArg), kecuali dengan tidak membuat array menengah. Ini sangat penting untuk setiap subclass array, seperti typed arrays, selama array menengah akan memiliki nilai yang terpisah agar bisa masuk ke tipe yang sesuai.

- -

Properti length dari method from() adalah 1.

- -

Contoh

- -
// Array-like object (arguments) to Array
-function f() {
-  return Array.from(arguments);
-}
-
-f(1, 2, 3);
-// [1, 2, 3]
-
-
-// Any iterable object...
-// Set
-var s = new Set(["foo", window]);
-Array.from(s);
-// ["foo", window]
-
-
-// Map
-var m = new Map([[1, 2], [2, 4], [4, 8]]);
-Array.from(m);
-// [[1, 2], [2, 4], [4, 8]]
-
-
-// String
-Array.from("foo");
-// ["f", "o", "o"]
-
-
-// Using an arrow function as the map function to
-// manipulate the elements
-Array.from([1, 2, 3], x => x + x);
-// [2, 4, 6]
-
-
-// Generate a sequence of numbers
-Array.from({length: 5}, (v, k) => k);
-// [0, 1, 2, 3, 4]
-
-
- -

Polyfill

- -

Array.from telah di masukkan di standar ECMA-262 pada edisi ke-6; karena itu mungkin tidak bisa digunakan pada implementasi standar lain. Anda bisa menyiasatinya dengan menambahkan kode berikut ke awal script, memungkinkan penggunaan Array.from pada implementasi yang aslinya tidak mendukung.  Algoritma ini sama dengan yang di spesifikasikan di ECMA-262, edisi ke-6, dengan saumsi Object dan TypeError memiliki nilai tersendiri dan callback.call mengevaluasi nilai valur dari {{jsxref("Function.prototype.call")}}. Selain itu, sejak iterable tidak dapat di polyfill, implementasi ini tidak mendukung generik iterable seperti yang didefinisikan di edisi ke-6 di ECMA-262.

- -
// Production steps of ECMA-262, Edition 6, 22.1.2.1
-// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
-if (!Array.from) {
-  Array.from = (function () {
-    var toStr = Object.prototype.toString;
-    var isCallable = function (fn) {
-      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
-    };
-    var toInteger = function (value) {
-      var number = Number(value);
-      if (isNaN(number)) { return 0; }
-      if (number === 0 || !isFinite(number)) { return number; }
-      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
-    };
-    var maxSafeInteger = Math.pow(2, 53) - 1;
-    var toLength = function (value) {
-      var len = toInteger(value);
-      return Math.min(Math.max(len, 0), maxSafeInteger);
-    };
-
-    // The length property of the from method is 1.
-    return function from(arrayLike/*, mapFn, thisArg */) {
-      // 1. Let C be the this value.
-      var C = this;
-
-      // 2. Let items be ToObject(arrayLike).
-      var items = Object(arrayLike);
-
-      // 3. ReturnIfAbrupt(items).
-      if (arrayLike == null) {
-        throw new TypeError("Array.from requires an array-like object - not null or undefined");
-      }
-
-      // 4. If mapfn is undefined, then let mapping be false.
-      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
-      var T;
-      if (typeof mapFn !== 'undefined') {
-        // 5. else
-        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
-        if (!isCallable(mapFn)) {
-          throw new TypeError('Array.from: when provided, the second argument must be a function');
-        }
-
-        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
-        if (arguments.length > 2) {
-          T = arguments[2];
-        }
-      }
-
-      // 10. Let lenValue be Get(items, "length").
-      // 11. Let len be ToLength(lenValue).
-      var len = toLength(items.length);
-
-      // 13. If IsConstructor(C) is true, then
-      // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
-      // 14. a. Else, Let A be ArrayCreate(len).
-      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
-
-      // 16. Let k be 0.
-      var k = 0;
-      // 17. Repeat, while k < len… (also steps a - h)
-      var kValue;
-      while (k < len) {
-        kValue = items[k];
-        if (mapFn) {
-          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
-        } else {
-          A[k] = kValue;
-        }
-        k += 1;
-      }
-      // 18. Let putStatus be Put(A, "length", len, true).
-      A.length = len;
-      // 20. Return A.
-      return A;
-    };
-  }());
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.from', 'Array.from')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("45")}}{{CompatGeckoDesktop("32")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}9.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("32")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/index.html b/files/id/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 2b052487c4..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,484 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - Global Objects - - JavaScript - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -

Objek JavaScript Array merupakan objek global yang berguna membangun himpunan; dimana merupakan objek level tinggi dan (seperti) daftar.

- -

Membuat sebuah Array

- -
var fruits = ["Apple", "Banana"];
-
-console.log(fruits.length);
-// 2
-
- -

Akses (index) kedalam sebuah item Array

- -
var first = fruits[0];
-// Apple
-
-var last = fruits[fruits.length - 1];
-// Banana
-
- -

Perulangan pada Array

- -
fruits.forEach(function (item, index, array) {
-  console.log(item, index);
-});
-// Apple 0
-// Banana 1
-
- -

Menambahkan elemen pada bagian akhir sebuah Array

- -
var newLength = fruits.push("Orange");
-// ["Apple", "Banana", "Orange"]
-
- -

Menghapus elemen di akhir sebuah Array

- -
var last = fruits.pop(); // remove Orange (from the end)
-// ["Apple", "Banana"];
-
- -

Menghapus elemen di awal sebuah Array

- -
var first = fruits.shift(); // remove Apple from the front
-// ["Banana"];
-
- -

Menambahkan elemen di bagian awal sebuah Array

- -
var newLength = fruits.unshift("Strawberry") // add to the front
-// ["Strawberry", "Banana"];
-
- -

Mencari (nomor) index elemen pada sebuah Array

- -
fruits.push("Mango");
-// ["Strawberry", "Banana", "Mango"]
-
-var pos = fruits.indexOf("Banana");
-// 1
-
- -

Menghapus elemen berdasar posisi index

- -
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
-// ["Strawberry", "Mango"]
-
- -

Menduplikat sebuah Array

- -
var shallowCopy = fruits.slice(); // this is how to make a copy
-// ["Strawberry", "Mango"]
-
- -

Syntax

- -
[element0, element1, ..., elementN]
-new Array(element0, element1[, ...[, elementN]])
-new Array(arrayLength)
- -
-
elementN
-
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below).Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
-
arrayLength
-
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
-
- -

Description

- -

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

- -

Some people think that you shouldn't use an array as an associative array. In any case, you can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post Lightweight JavaScript dictionaries with arbitrary keys as an example.

- -

Accessing array elements

- -

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.

- -
var arr = ['this is the first element', 'this is the second element'];
-console.log(arr[0]);              // logs 'this is the first element'
-console.log(arr[1]);              // logs 'this is the second element'
-console.log(arr[arr.length - 1]); // logs 'this is the second element'
-
- -

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:

- -
console.log(arr.0); // a syntax error
-
- -

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0);   // a syntax error
-console.log(years[0]);  // works properly
-
- -
renderer.3d.setTexture(model, 'character.png');     // a syntax error
-renderer['3d'].setTexture(model, 'character.png');  // works properly
-
- -

Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is for this reason that '2' and '02' would refer to two different slots on the years object and the following example could be true:

- -
console.log(years['2'] != years['02']);
-
- -

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation(but it can be accessed by dot notation in firefox 40.0a2 at least):

- -
var promise = {
-  'var'  : 'text',
-  'array': [1, 2, 3, 4]
-};
-
-console.log(promise['array']);
-
- -

Relationship between length and numerical properties

- -

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

- -
var fruits = [];
-fruits.push('banana', 'apple', 'peach');
-
-console.log(fruits.length); // 3
-
- -

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

- -
fruits[5] = 'mango';
-console.log(fruits[5]); // 'mango'
-console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
-console.log(fruits.length); // 6
-
- -

Increasing the {{jsxref("Array.length", "length")}}.

- -
fruits.length = 10;
-console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
-console.log(fruits.length); // 10
-
- -

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

- -
fruits.length = 2;
-console.log(Object.keys(fruits)); // ['0', '1']
-console.log(fruits.length); // 2
-
- -

This is explained further on the {{jsxref("Array.length")}} page.

- -

Creating an array using the result of a match

- -

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

- -
// Match one d followed by one or more b's followed by one d
-// Remember matched b's and the following d
-// Ignore case
-
-var myRe = /d(b+)(d)/i;
-var myArray = myRe.exec('cdbBdbsbz');
-
- -

The properties and elements returned from this match are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
- [2]: d
- -

Properties

- -
-
Array.length
-
The Array constructor's length property whose value is 1.
-
{{jsxref("Array.@@species", "get Array[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Array.prototype")}}
-
Allows the addition of properties to all array objects.
-
- -

Methods

- -
-
{{jsxref("Array.from()")}}
-
Creates a new Array instance from an array-like or iterable object.
-
{{jsxref("Array.isArray()")}}
-
Returns true if a variable is an array, if not false.
-
{{jsxref("Array.of()")}}
-
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
-
- -

Array instances

- -

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
- -

Methods

- -

Mutator methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
- -

Accessor methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
- -

Iteration methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
- -

Array generic methods

- -
-

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

-
- -

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

- -
function isLetter(character) {
-  return character >= 'a' && character <= 'z';
-}
-
-if (Array.prototype.every.call(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

- -
if (Array.every(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

- -

These are not part of ECMAScript standards (though the ES6 {{jsxref("Array.from()")}} can be used to achieve this). The following is a shim to allow its use in all browsers:

- -
// Assumes Array extras already present (one may use polyfills for these as well)
-(function() {
-  'use strict';
-
-  var i,
-    // We could also build the array of methods with the following, but the
-    //   getOwnPropertyNames() method is non-shimable:
-    // Object.getOwnPropertyNames(Array).filter(function(methodName) {
-    //   return typeof Array[methodName] === 'function'
-    // });
-    methods = [
-      'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
-      'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
-      'forEach', 'map', 'reduce', 'reduceRight', 'filter',
-      'some', 'every', 'find', 'findIndex', 'entries', 'keys',
-      'values', 'copyWithin', 'includes'
-    ],
-    methodCount = methods.length,
-    assignArrayGeneric = function(methodName) {
-      if (!Array[methodName]) {
-        var method = Array.prototype[methodName];
-        if (typeof method === 'function') {
-          Array[methodName] = function() {
-            return method.call.apply(method, arguments);
-          };
-        }
-      }
-    };
-
-  for (i = 0; i < methodCount; i++) {
-    assignArrayGeneric(methods[i]);
-  }
-}());
-
- -

Examples

- -

Creating an array

- -

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

- -
var msgArray = [];
-msgArray[0] = 'Hello';
-msgArray[99] = 'world';
-
-if (msgArray.length === 100) {
-  console.log('The length is 100.');
-}
-
- -

Creating a two-dimensional array

- -

The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

- -
var board = [
-  ['R','N','B','Q','K','B','N','R'],
-  ['P','P','P','P','P','P','P','P'],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  ['p','p','p','p','p','p','p','p'],
-  ['r','n','b','q','k','b','n','r'] ];
-
-console.log(board.join('\n') + '\n\n');
-
-// Move King's Pawn forward 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-console.log(board.join('\n'));
-
- -

Here is the output:

- -
R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
-p,p,p,p,p,p,p,p
-r,n,b,q,k,b,n,r
-
-R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , ,p, , ,
- , , , , , , ,
-p,p,p,p, ,p,p,p
-r,n,b,q,k,b,n,r
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}New method added: {{jsxref("Array.prototype.includes()")}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/array/isarray/index.html b/files/id/web/javascript/reference/global_objects/array/isarray/index.html deleted file mode 100644 index 152b6cdfd0..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/isarray/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Array.isArray() -slug: Web/JavaScript/Reference/Global_Objects/Array/isArray -tags: - - Array - - ECMAScript5 - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---- -
{{JSRef}}
- -

Method Array.isArray() mengembalikan nilai true jika objek adalah array, false jika bukan.

- -

Sintaks

- -
Array.isArray(obj)
- -

Parameter

- -
-
obj
-
Objek yang di cek.
-
- -

Deskripsi

- -

Baca artikel “Determining with absolute accuracy whether or not a JavaScript object is an array” untuk detailnya.

- -

Contoh

- -
// semuanya mengembalikan nilai true
-Array.isArray([]);
-Array.isArray([1]);
-Array.isArray(new Array());
-// Sekedar fakta : Array.prototype sendiri adalah array:
-Array.isArray(Array.prototype);
-
-// semua mengembalikan nilai false
-Array.isArray();
-Array.isArray({});
-Array.isArray(null);
-Array.isArray(undefined);
-Array.isArray(17);
-Array.isArray('Array');
-Array.isArray(true);
-Array.isArray(false);
-Array.isArray({ __proto__: Array.prototype });
-
- -

Polyfill

- -

Jalankan kode berikut sebelum kode lain untuk membuat method Array.isArray() jika secara native tidak tersedia.

- -
if (!Array.isArray) {
-  Array.isArray = function(arg) {
-    return Object.prototype.toString.call(arg) === '[object Array]';
-  };
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/join/index.html b/files/id/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index 8ddd3bb8ed..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -tags: - - Array - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -
{{JSRef}}
- -

Method join() menggabungkan semua elemen dari sebuah array menjadi sebuah string.

- -

Syntax

- -
str = arr.join([separator = ','])
- -

Parameter

- -
-
separator
-
Opsional. Menentukan string untuk memisahkan setiap elemen array. separator dapat di konersi ke string jika diperlukan. Jika dihilangkan, elemen array akan dipisahkan dengan koma, jika separator adalah string kosong, semua elemen digabungkan tanpa karakter pemisah.
-
- -

Deskripsi

- -

mengonversi string dari semua elemen array dengan menggabungkannya menjadi sebuah string. Jika elemen bernilai undefined atau null, akan dikonversi menjadi string kosong.

- -

Contoh

- -

Penggabungan array menggunakan empat cara yang berbeda

- -

Berikut merupakan contoh membuat array, dengan tiga elemen, kemudian menggabungkan array dengan empa cara berbeda : menggunakan separator default, koma dan spasi, plus dan string kosong.

- -
var a = ['Angin', 'Air', 'Api'];
-var variabel1 = a.join();      // Memberikan nilai 'Angin,Air,Api' pada variabel1
-var variabel2 = a.join(', ');  // Memberikan nilai 'Angin, Air, Api' pada variabel2
-var variabel3 = a.join(' + '); // Memberikan nilai 'Angin + Air + Api' pada variabel3
-var variabel4 = a.join('');    // Memberikan nilai 'AnginAirApi' pada variabel4
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Dasar{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/length/index.html b/files/id/web/javascript/reference/global_objects/array/length/index.html deleted file mode 100644 index 6e8e9e3ae8..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/length/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Array.length -slug: Web/JavaScript/Reference/Global_Objects/Array/length -tags: - - Array - - JavaScript - - Property - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Array/length ---- -
{{JSRef}}
- -

Properti array length merangkai atau mengembalikan angka dari sejumlah elemen pada array. berupa unsigned, 32-bit integer yang selalu lebih besar dari indeks array terbesar atau index array terakhir.

- -
var items = ["sepatu", "kaos", "baju", "sweater"];
-items.length;
-
-// index terakhir "sweater" 3
-// returns 4
- -

Deskripsi

- -

Nilai properti length berupa integer positif dan nilainya lebih kecil dari 2 sampai 2 pangkat 32 (232).

- -

Anda bisa merangkai properti length untuk memotong array kapanpun. Ketika anda memperpanjang array dengan mengubah properti length, nomor dari elemen sebenarnya tidak bertambah; contoh, jika anda merangkai length ke 3 ketika saat ini adalah 2, array tetap berisi 2 element. Dengan begitu, properti length tidak selalu menunjukkan jumlah angka dari nilai yang didefinisikan pada array. Lihat juga Hubungan antara length dan properti numerik.

- -

{{js_property_attributes(1, 0, 0)}}

- -

Contoh

- -

Iterasi pada array

- -

Pada contoh, numbers array diiterasikan melalui nilai properti array length. Nilai setiap elemen kemudian dikalikan.

- -
var numbers = [1, 2, 3, 4, 5];
-var length = numbers.length;
-for (var i = 0; i < length; i++) {
-  numbers[i] *= 2;
-}
-// numbers is now [2, 4, 6, 8, 10]
-
- -

Memendekan array

- -

Pada contoh memendekkan array numbers ke panjang array 3 jika panjang array sebenarnya lebih besar dari 3.

- -
var numbers = [1,2,3,4,5];
-
-if (numbers.length > 3) {
-  numbers.length = 3;
-}
-
-console.log(numbers); // [1, 2, 3]
-console.log(numbers.length); // 3
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/of/index.html b/files/id/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index 49ca553133..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -tags: - - Array - - JavaScript - - Method -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -

Method Array.of() membuat instansi Array baru denganjumlah variabel argumen.

- -

Perbedaan antara Array.of() dan konstruktor Array pada penanganan argumen integer: Array.of(42) membuat sebuah array dengan sebuah elemen, 42, sedang Array(42) membuat array dengan 42 element, yang masing - masing undefined.

- -

Sintaks

- -
Array.of(element0[, element1[, ...[, elementN]]])
- -

Parameter

- -
-
elementN
-
Element yang digunakan untuk membuat array.
-
- -

Deskripsi

- -

Fungsi ini merupakan bagian dari ECMAScript 6 standard. Untuk informasi lengkap lihat Array.of and Array.from proposal dan Array.of polyfill.

- -

Contoh

- -
Array.of(1);         // [1]
-Array.of(1, 2, 3);   // [1, 2, 3]
-Array.of(undefined); // [undefined]
-
- -

Polyfill

- -

Menjalankan kode berikut sebelum kode lain membuat Array.of() jika secara native tidak tersedia.

- -
if (!Array.of) {
-  Array.of = function() {
-    return Array.prototype.slice.call(arguments);
-  };
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.of', 'Array.of')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(45)}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(39)}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/pop/index.html b/files/id/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index f8dc9f0523..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -tags: - - Array - - JavaScript - - Method - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -
{{JSRef}}
- -

Method pop() menghapus elemen terakhir dari array dan mengembalikan elemen tersebut.

- -

Syntaks

- -
arr.pop()
- -

Deskripsi

- -

Method pop menghapus elemen terakhir pada array dan mengembalikan nilai ke pemanggil.

- -

pop adalah desain generic; method ini dapat berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} ke objek yang menyerupai array. Objek yang tidak memiliki properti length mencerminkan akhir dari urutan, properti numerik yang berbasis zero mungkin tidak memiliki makna yang berarti.

- -

jika anda menggunakan pop() pada array yang kosong, akan mengembalikan nilai {{jsxref("undefined")}}.

- -

Contoh

- -

Menghapus elemen terakhir pada array

- -

Kode berikut membuat array myFish yang memiliki empat elemen, kemudian menghapus elemen teakhirnya.

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-
-console.log(myFish); // ['angel', 'clown', 'mandarin', 'sturgeon']
-
-var popped = myFish.pop();
-
-console.log(myFish); // ['angel', 'clown', 'mandarin' ]
-
-console.log(popped); // 'sturgeon'
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/reverse/index.html b/files/id/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index dca16b463e..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -tags: - - Array - - Method -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -
{{JSRef}}
- -

Method reverse() membalikkan urutan array elemen. Elemen array pertama menjadi terakhir dan sebaliknya.

- -

Sintaks

- -
arr.reverse()
- -

Parameter

- -

None.

- -

Deskripsi

- -

Method reverse mengubah urutan elemen objek array, memutasi array, dan mengembalikan referensi ke array.

- -

Contoh

- -

Membalikan elemen di dalam array

- -

Pada contoh membuat array myArray dengan tiga elemen,  kemudian membalikkan array.

- -
var myArray = ['one', 'two', 'three'];
-myArray.reverse();
-
-console.log(myArray) // ['three', 'two', 'one']
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/shift/index.html b/files/id/web/javascript/reference/global_objects/array/shift/index.html deleted file mode 100644 index ac20d5cd60..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/shift/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.prototype.shift() -slug: Web/JavaScript/Reference/Global_Objects/Array/shift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift ---- -
{{JSRef}}
- -

method shift() menghapus elemen pertama pada array dan mengembalikan elemen tersebut. Method ini mengubah panjang (jumlah elemen) array.

- -

Sintaks

- -
arr.shift()
- -

Deskripsi

- -

Method shift menghapus elemen pada index 0 dan menggeser nilai index setelahnya, kemudian mengembalikan nilai yang dihapus. Jika properti {{jsxref("Array.length", "length")}} bernilai 0, maka akan mengembalikan nilai {{jsxref("undefined")}}.

- -

shift adalah desain generic; method ini dapat berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} pada objek yag menyerupai array. Objek yang tidak memiliki properti length akan dianggap terakhir dalam urutan, properti numerik berbasis zero mungkin tidak memiliki makna yang berarti.

- -

Contoh

- -

Menghapus Elemen dari sebuah Array

- -

Kode berikut menampilkan array myFish sebelum dan sesudah menghapus elemen pertama. Juga menampilkan elemen yang dihapus:

- -
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
-
-console.log('myFish sebelum: ' + myFish);
-// myFish sebelum: angel,clown,mandarin,surgeon
-
-var shifted = myFish.shift();
-
-console.log('myFish sesudah: ' + myFish);
-// myFish sesudah: clown,mandarin,surgeon
-
-console.log('Elemen yang dihapus: ' + shifted);
-// Elemen yang dihapus: angel
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ESDraft')}} 
- -

Kompabiltas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/slice/index.html b/files/id/web/javascript/reference/global_objects/array/slice/index.html deleted file mode 100644 index 44f018ba65..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/slice/index.html +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Array.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/Array/slice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice ---- -
{{JSRef}}
- -

Method slice() mengembalikan sebuah salinan dangkal dari sebagian array menjadi sebuah objek array baru yang dimulai dari start sampai end (end tidak termasuk) dimana start dan end merupakan index dari  item yang ada di  array tersebut. Tidak merubah array asli.

- -
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
- - - -

Sintaks

- -
arr.slice([start[, end]])
-
- -

Parameter

- -
-
start {{optional_inline}}
-
Indeks berbasis nol untuk memulai ekstraksi.
-

- Indeks negatif dapat digunakan, menunjukkan offset dari akhir urutan.. slice(-2) mengekstrak dua elemen terakhir dari urutan.
-
Jika start tidak terdefinisi, slice memulai dari indeks ke 0.
-
Jika start lebih besar dari indeks urutan, array kosong akan dikembalikan.
-
end {{optional_inline}}
-
Indeks berbasis nol untuk mengakhiri ekstraksi. slice mengekstrak hingga tapi tidak termasuk end. Sebagai contoh, slice(1,4) mengekstrak elemen kedua menuju elemen ke-empat (indeks elemen 1, 2, dan 3).
-
-

Indeks negatif bisa digunakan,
- menunjukkan offset dari akhir urutan. slice(2,-1) mengekstrak elemen ketiga menuju elemen kedua-ke-terakhir dalam urutan.

-
-
Jika end dihillangkan, slice mengekstrak melalui akhir dari urutan (arr.length).
-
Jika end lebih besar dari panjang urutan, slice mengkstrak melalui akhir urutan (arr.length).
-
- -

Return value

- -

Array baru berisi elemen yang diekstrak.

- -

Deskripsi

- -

slice does not alter the original array. It returns a shallow copy of elements from the original array. Elements of the original array are copied into the returned array as follows:

- - - -

If a new element is added to either array, the other array is not affected.

- -

Contoh

- -

Return a portion of an existing array

- -
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-let citrus = fruits.slice(1, 3)
-
-// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-// citrus contains ['Orange','Lemon']
-
- -

Using slice

- -

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

- -
// Using slice, create newCar from myCar.
-let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
-let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
-let newCar = myCar.slice(0, 2)
-
-// Display the values of myCar, newCar, and the color of myHonda
-//  referenced from both arrays.
-console.log('myCar = ' + JSON.stringify(myCar))
-console.log('newCar = ' + JSON.stringify(newCar))
-console.log('myCar[0].color = ' + myCar[0].color)
-console.log('newCar[0].color = ' + newCar[0].color)
-
-// Change the color of myHonda.
-myHonda.color = 'purple'
-console.log('The new color of my Honda is ' + myHonda.color)
-
-// Display the color of myHonda referenced from both arrays.
-console.log('myCar[0].color = ' + myCar[0].color)
-console.log('newCar[0].color = ' + newCar[0].color)
-
- -

This script writes:

- -
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
-         'cherry condition', 'purchased 1997']
-newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
-myCar[0].color = red
-newCar[0].color = red
-The new color of my Honda is purple
-myCar[0].color = purple
-newCar[0].color = purple
-
- -

Array-like objects

- -

slice method can also be called to convert Array-like objects/collections to a new Array. You just {{jsxref("Function.prototype.bind", "bind")}} the method to the object. The {{jsxref("Functions/arguments", "arguments")}} inside a function is an example of an 'array-like object'.

- -
function list() {
-  return Array.prototype.slice.call(arguments)
-}
-
-let list1 = list(1, 2, 3) // [1, 2, 3]
-
- -

Binding can be done with the {{jsxref("Function.prototype.call", "call()")}} method of {{jsxref("Function.prototype")}} and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call.

- -

Anyway, it can be simplified using {{jsxref("Function.prototype.bind", "bind")}}.

- -
let unboundSlice = Array.prototype.slice
-let slice = Function.prototype.call.bind(unboundSlice)
-
-function list() {
-  return slice(arguments)
-}
-
-let list1 = list(1, 2, 3) // [1, 2, 3]
- -

Spesifikasi

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}
- -

Kompatibilitas Peramban

- - - -

{{Compat("javascript.builtins.Array.slice")}}

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/splice/index.html b/files/id/web/javascript/reference/global_objects/array/splice/index.html deleted file mode 100644 index a0c7c1cb86..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/splice/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Array.prototype.splice() -slug: Web/JavaScript/Reference/Global_Objects/Array/splice -tags: - - Indonesia -translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---- -
{{JSRef}}
- -

Metode splice() mengubah konten dari array dengan menghapus elemen yang ada dan/atau menambah elemen baru.

- -
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
- -

Syntax

- -
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
-
- -

Parameters

- -
-
start
-
Indeks di mana untuk mulai mengubah array (dengan asal 0). Jika lebih besar dari panjang array, indeks awal sebenarnya akan diatur ke panjang array. Jika negatif, akan mulai banyak elemen dari akhir array (dengan asal -1) dan akan diset ke 0 jika nilai absolut lebih besar dari panjang array.
-
deleteCount {{optional_inline}}
-
Sebuah integer yang menunjukkan jumlah elemen array lama yang akan dihapus.
-
Jika deleteCount dihilangkan, atau jika nilainya lebih besar dari array.length - start (yaitu, jika lebih besar dari jumlah elemen yang tersisa dalam array, mulai dari start), maka semua elemen dari start sampai akhir dari array akan dihapus.
-
Jika deleteCount adalah 0 atau negatif, tidak ada elemen yang dihapus. Dalam kasus ini, Anda harus menentukan setidaknya satu elemen baru (lihat di bawah).
-
item1, item2, ... {{optional_inline}}
-
Elemen yang ditambahkan ke array, dimulai pada indeks awal. Jika kamu tidak menentukan elemen apapun, splice() hanya akan menghapus elemen-elemen dari array.
-
- -

Return value

- -

Array berisi elemen yang dihapus. Jika hanya satu elemen yang dihapus, array dari satu elemen dikembalikan. Jika tidak ada elemen yang dihapus, sebuah array kosong akan dikembalikan.

- -

Deskripsi

- -

Jika anda menentukan elemen yang berbeda untuk disisipkan daripada nomor yang anda hapus, array akan memiliki panjang yang berbeda ketika kamu memanggilnya nanti.

- -

Contoh

- -

Remove 0 elements from index 2, and insert "drum"

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum');
-
-// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
-// removed is [], no elements removed
-
- -

Remove 1 element from index 3

- -
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(3, 1);
-
-// removed is ["mandarin"]
-// myFish is ["angel", "clown", "drum", "sturgeon"]
-
- -

Remove 1 element from index 2, and insert "trumpet"

- -
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
-var removed = myFish.splice(2, 1, 'trumpet');
-
-// myFish is ["angel", "clown", "trumpet", "sturgeon"]
-// removed is ["drum"]
- -

Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"

- -
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
-var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
-
-// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
-// removed is ["angel", "clown"]
- -

Remove 2 elements from index 2

- -
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
-var removed = myFish.splice(myFish.length - 3, 2);
-
-// myFish is ["parrot", "anemone", "sturgeon"]
-// removed is ["blue", "trumpet"]
- -

Remove 1 element from index -2

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(-2, 1);
-
-// myFish is ["angel", "clown", "sturgeon"]
-// removed is ["mandarin"]
- -

Remove all elements after index 2 (incl.)

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2);
-
-// myFish is ["angel", "clown"]
-// removed is ["mandarin", "sturgeon"]
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.splice")}}

-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/array/unshift/index.html b/files/id/web/javascript/reference/global_objects/array/unshift/index.html deleted file mode 100644 index 4df2069f54..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/unshift/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Array.prototype.unshift() -slug: Web/JavaScript/Reference/Global_Objects/Array/unshift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---- -
{{JSRef}}
- -

Method unshift() menambahkan satu atau lebih elemen ke indek awal array dan mengembalikan jumlah index array yang baru.

- -

Sintaks

- -
arr.unshift([element1[, ...[, elementN]]])
- -

Parameter

- -
-
elementN
-
Elemen yang akan di tambahkan di awal array.
-
- -

Returns

- -

Properti {{jsxref("Array.length", "length")}} baru dari objek teratas dimana method di panggil.

- -

Deskripsi

- -

Method unshift menambahkan nilai yang diberikan ke awal objek array.

- -

unshift biasanya generic; method ini bisa berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} ke objek menyerupai array. Objek yang tidak memiliki properti length mencerminkan dari serangkaian urutan, properti numerik berbasis zero kemungkinan tidak berperilaku dengan cara yang berarti.

- -

Contoh

- -
var arr = [1, 2];
-
-arr.unshift(0); // result of call is 3, the new array length
-// arr is [0, 1, 2]
-
-arr.unshift(-2, -1); // = 5
-// arr is [-2, -1, 0, 1, 2]
-
-arr.unshift([-3]);
-// arr is [[-3], -2, -1, 0, 1, 2]
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/values/index.html b/files/id/web/javascript/reference/global_objects/array/values/index.html deleted file mode 100644 index dd77cc65a5..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/values/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: Array.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Array/values -translation_of: Web/JavaScript/Reference/Global_Objects/Array/values ---- -
{{JSRef}}
- -

Method values() mengembalikan objek Array Iterator baru yang berisi nilai setiap index pada array.

- -

Sintaks

- -
arr.values()
- -

Contoh

- -

Iterasi menggunakan for...of loop

- -
var arr = ['w', 'y', 'k', 'o', 'p'];
-var eArr = arr.values();
-// your browser must support for..of loop
-// and let-scoped variables in for loops
-for (let letter of eArr) {
-  console.log(letter);
-}
-
- -

Iterasi alternatif

- -
var arr = ['w', 'y', 'k', 'o', 'p'];
-var eArr = arr.values();
-console.log(eArr.next().value); // w
-console.log(eArr.next().value); // y
-console.log(eArr.next().value); // k
-console.log(eArr.next().value); // o
-console.log(eArr.next().value); // p
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("51")}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatNo}}9
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("51")}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html deleted file mode 100644 index 08e657aeec..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Date.prototype.getFullYear() -slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear -tags: - - Date - - JavaScript - - Metode - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear ---- -
{{JSRef}}
- -

Metode getFullYear() mengembanlikan tahun dari tanggal yang dispesifikasi, mengikuti waktu lokal.

- -

Gunakan metode ini ketimbang metode {{jsxref("Date.prototype.getYear()", "getYear()")}}.

- -
{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}
- - - -

Syntax

- -
dateObj.getFullYear()
- -

Nilai kembali

- -

Angka yang berkorespondensi ke tahuny dari tanggal yang diberikan, mengikuti waktu lokal.

- -

Deskripsi

- -

Nilai yang dikembalikan oleh getFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.

- -

Contoh

- -

Menggunakan getFullYear()

- -

Contoh ini menggassign nilai empat-digit dari tahun saat ini ke variabel year.

- -
var today = new Date();
-var year = today.getFullYear();
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomen
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi inisial. Diimplementasi di JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- - - -

{{Compat("javascript.builtins.Date.getFullYear")}}

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/index.html b/files/id/web/javascript/reference/global_objects/date/index.html deleted file mode 100644 index 1fc6272dcf..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: Date -slug: Web/JavaScript/Reference/Global_Objects/Date -tags: - - Date - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Date ---- -
{{JSRef}}
- -

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

- -

Syntax

- -
new Date();
-new Date(value);
-new Date(dateString);
-new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
-
- -
-

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the {{jsxref("Operators/new", "new")}} operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

-
- -

Parameters

- -
-

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

-
- -
-

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) with the same arguments.

-
- -
-
value
-
Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).
-
dateString
-
String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601). -
-

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

-
-
-
year
-
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the {{anch("Example:_Two_digit_years_map_to_1900_-_1999", "example below")}}.
-
month
-
Integer value representing the month, beginning with 0 for January to 11 for December.
-
day
-
Optional. Integer value representing the day of the month.
-
hour
-
Optional. Integer value representing the hour of the day.
-
minute
-
Optional. Integer value representing the minute segment of a time.
-
second
-
Optional. Integer value representing the second segment of a time.
-
millisecond
-
Optional. Integer value representing the millisecond segment of a time.
-
- -

Description

- - - -

Properties

- -
-
{{jsxref("Date.prototype")}}
-
Allows the addition of properties to a JavaScript Date object.
-
Date.length
-
The value of Date.length is 7. This is the number of arguments handled by the constructor.
-
- -

Methods

- -
-
{{jsxref("Date.now()")}}
-
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
-
{{jsxref("Date.parse()")}}
-
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. -
-

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

-
-
-
{{jsxref("Date.UTC()")}}
-
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC.
-
- -

JavaScript Date instances

- -

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

- -

Date.prototype Methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
- -

Examples

- -

Several ways to create a Date object

- -

The following examples show several ways to create JavaScript dates:

- -
-

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

-
- -
var today = new Date();
-var birthday = new Date('December 17, 1995 03:24:00');
-var birthday = new Date('1995-12-17T03:24:00');
-var birthday = new Date(1995, 11, 17);
-var birthday = new Date(1995, 11, 17, 3, 24, 0);
-
- -

Two digit years map to 1900 - 1999

- -

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

- -
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
-
-// Deprecated method, 98 maps to 1998 here as well
-date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
-
-date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
-
- -

Calculating elapsed time

- -

The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.

- -

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

- -
// using Date objects
-var start = Date.now();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = Date.now();
-var elapsed = end - start; // elapsed time in milliseconds
-
- -
// using built-in methods
-var start = new Date();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = new Date();
-var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
-
- -
// to test a function and get back its return
-function printElapsedTime(fTest) {
-  var nStartTime = Date.now(),
-      vReturn = fTest(),
-      nEndTime = Date.now();
-
-  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
-  return vReturn;
-}
-
-yourFunctionReturn = printElapsedTime(yourFunction);
-
- -
-

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Some browsers can have issues when parsing dates: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

- -

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

diff --git a/files/id/web/javascript/reference/global_objects/date/now/index.html b/files/id/web/javascript/reference/global_objects/date/now/index.html deleted file mode 100644 index 43760a275b..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/now/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Date.now() -slug: Web/JavaScript/Reference/Global_Objects/Date/now -tags: - - Date - - JavaScript - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/now ---- -
{{JSRef}}
- -

Method Date.now() mengembalikan jumlah milisekon sejak 1 Januari 1970 00:00:00 UTC.

- -

Sintaks

- -
var timeInMs = Date.now();
- -

Parameter

- -

None.

- -

Deskripsi

- -

Method now() mengembalikan nilaimillisekon sejak 1 January 1970 00:00:00 UTC hingga sekarang sebagai {{jsxref("Number")}}.

- -

Karena now() adalah method static dari {{jsxref("Date")}}, anda bisa menggunakannya sebagai Date.now().

- -

Polyfill

- -

Method ini di bakukan pada ECMA-262 5th edition. Mesin yang belum diupdate untuk mendukung method ini bisa menggunkan shim berikut:

- -
if (!Date.now) {
-  Date.now = function now() {
-    return new Date().getTime();
-  };
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9")}}{{CompatIE("9")}}{{CompatOpera("10.50")}}{{CompatSafari("4")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/tojson/index.html b/files/id/web/javascript/reference/global_objects/date/tojson/index.html deleted file mode 100644 index cb951d5fa0..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/tojson/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Date.prototype.toJSON() -slug: Web/JavaScript/Reference/Global_Objects/Date/toJSON -tags: - - Date - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/toJSON ---- -
{{JSRef}}
- -

Method toJSON() mengembalikan string berdasarkan pada object {{jsxref("Date")}}.

- -

Syntax

- -
dateObj.toJSON()
- -

Deskripsi

- -

{{jsxref("Date")}} mengacu pada titik waktu tertentu. Memanggil toJSON() mengembalikan nilai ke string (menggunakan {{jsxref("Date.prototype.toISOString()", "toISOString()")}}) berdasarkan nilai pada object {{jsxref("Date")}}. Method ini biasanya ditujukan, secara default, guna menserialisasi object {{jsxref("Date")}} saat serialisasi {{Glossary("JSON")}}.

- -

Contoh

- -

Penggunaan toJSON()

- -
var jsonDate = (new Date()).toJSON();
-var backToDate = new Date(jsonDate);
-
-console.log(jsonDate); //2015-10-26T07:46:36.611Z
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.9.5.44', 'Date.prototype.toJSON')}}{{Spec2('ES5.1')}}Definisi Inisial. Diimplementasikan dalam JavaScript 1.8.5.
{{SpecName('ES6', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/totimestring/index.html b/files/id/web/javascript/reference/global_objects/date/totimestring/index.html deleted file mode 100644 index 90ebd23e68..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/totimestring/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Date.prototype.toTimeString() -slug: Web/JavaScript/Reference/Global_Objects/Date/toTimeString -tags: - - Date - - JavaScript - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/toTimeString ---- -
{{JSRef}}
- -

Method toTimeString() mengembalikan satuan waktu dari objek {{jsxref("Date")}} object dalam format yang dapat dibaca manusia.

- -

Sintaks

- -
dateObj.toTimeString()
- -

Deskripsi

- -

Instansi {{jsxref("Date")}} menunjuk pada titik waktu spesifik. Dengan memanggil {{jsxref("Date.prototype.toString()", "toString()")}} akan mengembalikan format tanggal dalam bentuk yang mudah dibaca manuasia dengan format tanggal English (Amerika). Di SpiderMonkey, Bagian tanggal terdiri dari (hari, bulan, dan tahun) di ikuti dengan waktu (Jam, menit, detik, dan waktu bagian). Terkadang kita hanya membutuhan bagian waktu dalam bentuk string; hal tersebut bisa di capai dengan menggunakan metod toTimeString().

- -

Method toTimeString() sangatlah berguna karena berdasarkan engine (compiliant engine) yang di implementasikan ECMA-262 mungkin string yang diperoleh akan berbeda dari {{jsxref("Date.prototype.toString()", "toString()")}} untuk objek {{jsxref("Date")}}, dengan format tergantung dari implementasi; pendekatan bagian string sederhana kemungkinan tidak sama untuk engine yang berbeda.

- -

Contoh

- -

Dasar penggunaan of toTimeString()

- -
var d = new Date(1993, 6, 28, 14, 39, 7);
-
-console.log(d.toString());     // logs Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
-console.log(d.toTimeString()); // logs 14:39:07 GMT-0600 (PDT)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.9.5.4', 'Date.prototype.toTimeString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.totimestring', 'Date.prototype.toTimeString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.totimestring', 'Date.prototype.toTimeString')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/error/index.html b/files/id/web/javascript/reference/global_objects/error/index.html deleted file mode 100644 index c0fc3cec6f..0000000000 --- a/files/id/web/javascript/reference/global_objects/error/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Error -slug: Web/JavaScript/Reference/Global_Objects/Error -tags: - - Error - - JavaScript - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Error ---- -
{{JSRef}}
- -

Konstruktor Error membuat sebuah objek error. Misal objek Error di lontarkan ketika terjadi runtime error. Objek Error juga dapat digunakan sebagai objek dasar dengan pengecualian yang ditentukan pengguna. Berikut untuk standard jenis built-in error.

- -

Sintaks

- -
new Error([message[, fileName[, lineNumber]]])
- -

Parameter

- -
-
message
-
Optional. Human-readable description of the error.
-
fileName {{non-standard_inline}}
-
Optional. The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor.
-
lineNumber {{non-standard_inline}}
-
Optional. The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation.
-
- -

Description

- -

Runtime errors result in new Error objects being created and thrown.

- -

This page documents the use of the Error object itself and its use as a constructor function. For a list of properties and methods inherited by Error instances, see {{jsxref("Error.prototype")}}.

- -

Error types

- -

Besides the generic Error constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see Exception Handling Statements.

- -
-
{{jsxref("EvalError")}}
-
Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("InternalError")}} {{non-standard_inline}}
-
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
-
{{jsxref("RangeError")}}
-
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
-
{{jsxref("ReferenceError")}}
-
Creates an instance representing an error that occurs when de-referencing an invalid reference.
-
{{jsxref("SyntaxError")}}
-
Creates an instance representing a syntax error that occurs while parsing code in {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("TypeError")}}
-
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
-
{{jsxref("URIError")}}
-
Creates an instance representing an error that occurs when {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} or {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} are passed invalid parameters.
-
- -

Properties

- -
-
{{jsxref("Error.prototype")}}
-
Allows the addition of properties to Error instances.
-
- -

Methods

- -

The global Error object contains no methods of its own, however, it does inherit some methods through the prototype chain.

- -

Error instances

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}
- -

Properties

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}
- -

Methods

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}
- -

Examples

- -

Throwing a generic error

- -

Usually you create an Error object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct:

- -
try {
-  throw new Error('Whoops!');
-} catch (e) {
-  console.log(e.name + ': ' + e.message);
-}
-
- -

Handling a specific error

- -

You can choose to handle only specific error types by testing the error type with the error's {{jsxref("Object.prototype.constructor", "constructor")}} property or, if you're writing for modern JavaScript engines, {{jsxref("Operators/instanceof", "instanceof")}} keyword:

- -
try {
-  foo.bar();
-} catch (e) {
-  if (e instanceof EvalError) {
-    console.log(e.name + ': ' + e.message);
-  } else if (e instanceof RangeError) {
-    console.log(e.name + ': ' + e.message);
-  }
-  // ... etc
-}
-
- -

Custom Error Types

- -

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. The common way to do this is demonstrated below.

- -
-

Note that the thrown MyError will report incorrect lineNumber and fileName at least in Firefox.

-
- -

See also the "What's a good way to extend Error in JavaScript?" discussion on Stackoverflow.

- -
// Create a new object, that prototypically inherits from the Error constructor
-function MyError(message) {
-  this.name = 'MyError';
-  this.message = message || 'Default Message';
-  this.stack = (new Error()).stack;
-}
-MyError.prototype = Object.create(Error.prototype);
-MyError.prototype.constructor = MyError;
-
-try {
-  throw new MyError();
-} catch (e) {
-  console.log(e.name);     // 'MyError'
-  console.log(e.message);  // 'Default Message'
-}
-
-try {
-  throw new MyError('custom message');
-} catch (e) {
-  console.log(e.name);     // 'MyError'
-  console.log(e.message);  // 'custom message'
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error-objects', 'Error')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/error/name/index.html b/files/id/web/javascript/reference/global_objects/error/name/index.html deleted file mode 100644 index 6644fff80a..0000000000 --- a/files/id/web/javascript/reference/global_objects/error/name/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Error.prototype.name -slug: Web/JavaScript/Reference/Global_Objects/Error/name -tags: - - Error - - JavaScript - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Error/name ---- -
{{JSRef}}
- -

Properti name menyatakan nama dari jenis error. Nilai awalnya adalah "Error".

- -

Deskripsi

- -

Secara default, misalnya {{jsxref("Error")}} diberi nama "Error". Properti name, sebagai tambahan utuk properti {{jsxref("Error.prototype.message", "message")}}, digunakan oleh method {{jsxref("Error.prototype.toString()")}} untuk membuat sebuah pernyataan dalam bentuk string yang menyatakan error.

- -

Contoh

- -

Menggunakan custom error

- -
var e = new Error('Inputan tidak lengkap'); // e.name nilainya 'Error'
-
-e.name = 'ParseError';
-throw e;
-// e.toString() akan mengembalikan 'ParseError: Inputan tidak lengkap'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.4.2', 'Error.prototype.name')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/displayname/index.html b/files/id/web/javascript/reference/global_objects/function/displayname/index.html deleted file mode 100644 index 952014983b..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/displayname/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Function.displayName -slug: Web/JavaScript/Reference/Global_Objects/Function/displayName -tags: - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/displayName ---- -
{{JSRef}} {{non-standard_header}}
- -

Properti function.displayName mengembalikan nama fungsi.

- -

Deskripsi

- -

Ketika didefinisikan, properti displayName mengembalikan nama dari sebuah fungsi:

- -
function doSomething() {}
-
-console.log(doSomething.displayName); // "undefined"
-
-var popup = function(content) { console.log(content); };
-
-popup.displayName = 'Show Popup';
-
-console.log(popup.displayName); // "Show Popup"
-
- -

Anda bisa mendefinisikan sebuah fungsi dengan sebuah display nama di {{jsxref("Functions", "function expression", "", 1)}}:

- -
var object = {
-  someMethod: function() {}
-};
-
-object.someMethod.displayName = 'someMethod';
-
-console.log(object.someMethod.displayName); // logs "someMethod"
-
-try { someMethod } catch(e) { console.log(e); }
-// ReferenceError: someMethod is not defined
-
- -

Anda bisa merubah  displayName dari sebuah fungsi secara dinamis:

- -
var object = {
-  // anonymous
-  someMethod: function(value) {
-    this.displayName = 'someMethod (' + value + ')';
-  }
-};
-
-console.log(object.someMethod.displayName); // "undefined"
-
-object.someMethod('123')
-console.log(object.someMethod.displayName); // "someMethod (123)"
-
- -

Contoh

- -

Biasanya lebih banyak digunakan dengan console dan profiler melalui {{jsxref("Function.name", "func.name")}} untuk menampilkan nama function.

- -

Dengan menuliskan kode berikut, maka seharusnya akan menampilkan "function My Function()":

- -
var a = function() {};
-a.displayName = 'My Function';
-
-a; // "function My Function()"
- -

Spesifikasi

- -

Bukan bagian dari spesifikasi.

- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(13)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
diff --git a/files/id/web/javascript/reference/global_objects/function/index.html b/files/id/web/javascript/reference/global_objects/function/index.html deleted file mode 100644 index 49d1c1a114..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Function -slug: Web/JavaScript/Reference/Global_Objects/Function -tags: - - Constructor - - Function - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Function ---- -
{{JSRef}}
- -

Konstruktor Function membuat sebuah objek Function baru. Di Javascript setiap fungsi adalah sebuah objek Function.

- -

Sintaks

- -
new Function ([arg1[, arg2[, ...argN]],] functionBody)
- -

Parameter

- -
-
arg1, arg2, ... argN
-
Nama yang akan digunakan oleh fungsi sebagai nama formal argumen. Masing-masing harus berupa string yang sesuai dengan identifier JavaScript yang valid atau daftar string dipisahkan dengan koma; contohnya "x", "theValue", atau "a,b".
-
functionBody
-
String berisi sintaks JavaScript yang terdiri dari definisi fungsi.
-
- -

Deskripsi

- -

Objek  Function yang dibuat dengan konstruktor Function diuraikan ketika fungsi dibuat. Hal tersebut kurang efisien dibandingkan dengan mendeklarasikan fungsi dengan function expression atau function statement dan memanggilnya dengan kode Anda, karena fungsi-fungsi tersebut diuraikan dengan sisa kode.

- -

Semua argumen yang diteruskan ke fungsi diperlakukan sebagai nama identifier parameter dalam fungsi yang akan dibuat, dalam urutan yang dilewatkan.

- -
-

Catatan: Fungsi dibuat dengan konstruktor Function  jangan membuat penutup pada konteks kreasi mereka; Mereka selalu dibuat dalam ruang lingkup global. Saat menjalankannya, mereka hanya bisa mengakses variabel lokal mereka sendiri dan variabel global, bukan variabel dari ruang lingkup dimana konstruktor Function dipanggil. Berbeda dari menggunakan {{jsxref("eval")}} dengan kode untuk fungsi ekspresi.

-
- -

memanggil konstruktor Function sebagai sebuah fungsi (tanpa menggunakan operatur baru) mempunyai efek yang sama seperti memanggilnya sebagai konstruktor

- -

Properti dan Method Function

- -

Objek Function global tidak memiliki method atau properti sendiri. Namun, fungsi itu sendiri mewarisi beberapa method dan properti melalui prototipe dari {{jsxref("Function.prototype")}}.

- -

Objek prototipe Function

- -

Properti

- -
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
- -

Method

- -
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
- -

Function instances

- -

Function instances mewarisi method dan properti dari {{jsxref("Function.prototype")}}. Seperti halnya semua konstruktor, Anda dapat mengubah objek prototipe konstruktor untuk membuat perubahan pada semua Function instances.

- -

Contoh

- -

Menentukan arguman dengan konstruktor Function

- -

Dibawah ini kode untuk membuat sebuah objek Function yang menggunakan dua argumen.

- -
// Contoh dapat dijalankan langsung di konsol JavaScript Anda
-
-// Buat fungsi yang mengambil dua argumen dan mengembalikan jumlah argumen tersebut
-var adder = new Function('a', 'b', 'return a + b');
-
-// Memanggil fungsi
-adder(2, 6);
-// > 8
-
- -

Argumen "a" dan "b" adalah nama argumen formal yang digunakan pada function body "return a + b".

- -

Pintasan rekursif untuk memofikasi DOM secara masif

- -

Membuat fungsi dengan konstruktor Function adalah salah satu cara dinamis untuk membuat objek baru dengan beberapa kode yang dapat dieksekusi ke dalam lingkup global dari suatu fungsi. Contoh berikut (pintasan rekursif untuk memodifikasi DOM secara masif) tidak dimungkinkan tanpa permintaan konstruktor Function untuk setiap kueri baru jika Anda ingin menghindari penutup tiap fungsi.

- -
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
-<script type="text/javascript">
-var domQuery = (function() {
-  var aDOMFunc = [
-    Element.prototype.removeAttribute,
-    Element.prototype.setAttribute,
-    CSSStyleDeclaration.prototype.removeProperty,
-    CSSStyleDeclaration.prototype.setProperty
-  ];
-
-  function setSomething(bStyle, sProp, sVal) {
-    var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
-        aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
-        aNodeList = bStyle ? this.cssNodes : this.nodes;
-
-    if (bSet && bStyle) { aArgs.push(''); }
-    for (
-      var nItem = 0, nLen = this.nodes.length;
-      nItem < nLen;
-      fAction.apply(aNodeList[nItem++], aArgs)
-    );
-    this.follow = setSomething.caller;
-    return this;
-  }
-
-  function setStyles(sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
-  function setAttribs(sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
-  function getSelectors() { return this.selectors; };
-  function getNodes() { return this.nodes; };
-
-  return (function(sSelectors) {
-    var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
-    oQuery.selectors = sSelectors;
-    oQuery.nodes = document.querySelectorAll(sSelectors);
-    oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function(oInlineCSS) { return oInlineCSS.style; });
-    oQuery.attributes = setAttribs;
-    oQuery.inlineStyle = setStyles;
-    oQuery.follow = getNodes;
-    oQuery.toString = getSelectors;
-    oQuery.valueOf = getNodes;
-    return oQuery;
-  });
-})();
-</script>
-</head>
-
-<body>
-
-<div class="testClass">Lorem ipsum</div>
-<p>Some text</p>
-<div class="testClass">dolor sit amet</div>
-
-<script type="text/javascript">
-domQuery('.testClass')
-  .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
-  .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
-</script>
-</body>
-
-</html>
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
- -

Kesesuaian Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/length/index.html b/files/id/web/javascript/reference/global_objects/function/length/index.html deleted file mode 100644 index 901c11b336..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/length/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Function.length -slug: Web/JavaScript/Reference/Global_Objects/Function/length -tags: - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/length ---- -
{{JSRef}}
- -

Properti length menentukan jumlah argumen yang diharapkan oleh fungsi.

- -
{{js_property_attributes(0,0,1)}}
- -

Deskripsi

- -

length merupakan properti dari objek fungsi, dan mengindikasikan berapa banyak argumen yang diharapkan fungsi, mis. jumlah parameter formal. Jumlah ini mengesampingkan {{jsxref("rest_parameters", "rest parameter", "", 1)}}. Sebaliknya, {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} adalah lokal untuk fungsi dan memberikan jumlah argumen sebenarnya ke fungsi.

- -

Properti data dari constructor Function

- -

Construktor {{jsxref("Function")}} sendiri adalah objek {{jsxref("Function")}}. data properti length bernilai 1. Properti atribut: Writable: false, Enumerable: false, Configurable: true.

- -

Properti dari Function prototype object

- -

Panjang properti dari prototype objek {{jsxref("Function")}} bernilai 0.

- -

Contoh

- -
console.log(Function.length); /* 1 */
-
-console.log((function()        {}).length); /* 0 */
-console.log((function(a)       {}).length); /* 1 */
-console.log((function(a, b)    {}).length); /* 2 etc. */
-
-console.log((function(...args) {}).length);
-// 0, rest parameter is not counted
-
-console.log((function(a, b = 1, c) {}).length);
-// 1, only parameters before the first one with
-// a default value is counted
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}The configurable attribute of this property is now true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatGeckoDesktop(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/name/index.html b/files/id/web/javascript/reference/global_objects/function/name/index.html deleted file mode 100644 index 1a35d62020..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/name/index.html +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: Function.name -slug: Web/JavaScript/Reference/Global_Objects/Function/name -tags: - - ECMAScript6 - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/name ---- -
{{JSRef}}
- -

Properti function.name mengembalikan nama fungsi.

- -
{{js_property_attributes(0,0,1)}}
- -
Perlu di ingat bahwa ini di dalam non-standard, implementasi pre-ES6 atribut configurable juga false.
- -

Deskripsi

- -

Properti name property mengembalikan nama sebuah fungsi , atau (sebelum implementasi ES6) string kosong untuk anonymous functions:

- -
function doSomething() {}
-
-console.log(doSomething.name); // logs "doSomething"
-
- -

Fungsi di buat menggunakan sintaks new Function(...) atau hanya Function(...) memiliki properti name di set empty string. Pada contoh anonymous functions dibuat, sehingga name mengembalikan empty string:

- -
var f = function() {};
-var object = {
-  someMethod: function() {}
-};
-
-console.log(f.name == ''); // true
-console.log(object.someMethod.name == ''); // also true
-
- -

Browser yang mengimplementasikan fungsi ES6 mengambil nama dari anonymous function dari posisi syntactic-nya. Contoh:

- -
var f = function() {};
-console.log(f.name); // "f"
- -

Anda bisa mendefinisikan sebuah fungsi dengan nama di {{jsxref("Operators/Function", "function expression", "", 1)}}:

- -
var object = {
-  someMethod: function object_someMethod() {}
-};
-console.log(object.someMethod.name); // logs "object_someMethod"
-
-try { object_someMethod } catch(e) { console.log(e); }
-// ReferenceError: object_someMethod is not defined
-
- -

Anda tidak bisa mengubah nama fungsi, Properti ini hanya bisa dibaca:

- -
var object = {
-  // anonymous
-  someMethod: function() {}
-};
-
-object.someMethod.name = 'someMethod';
-console.log(object.someMethod.name); // empty string, someMethod is anonymous
-
- -

Untuk mengubah, anda perlu menggunakan {{jsxref("Object.defineProperty()")}}.

- -

Contoh

- -

Anda bisa menggunakan obj.constructor.name untuk memeriksa "class" dari sebuah objek:

- -
function a() {}
-
-var b = new a();
-
-console.log(b.constructor.name); // logs "a"
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-name', 'name')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-name', 'name')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(33.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatChrome(43.0)}}{{CompatGeckoDesktop(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatNo}}{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(51.0)}}
-
- -

[1] See {{bug(883377)}}.

diff --git a/files/id/web/javascript/reference/global_objects/index.html b/files/id/web/javascript/reference/global_objects/index.html deleted file mode 100644 index 5259bde5b8..0000000000 --- a/files/id/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Global Objek -slug: Web/JavaScript/Reference/Global_Objects -tags: - - JavaScript - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects ---- -
{{jsSidebar("Objects")}}
- -

Pada bagian ini membahas standar javascript, objek built-in, Termasuk didalamnya method dan properti.

- -
-

Istilah "Global Objek" (atau standar objek built-in)disini bukan berarti Global Objek. Disini global objek di artikan sebagai objek pada scope global (tapi hanya jika ECMAScript 5 mode strict tidak digunakan; pada kasus ini mengembalikan {{jsxref("undefined")}}).  Global objek sendiri bisa di akses menggunakan operator {{jsxref("Operators/this", "this")}} pada lingkup global. Bahkan, lingkup global terdiri dari properti pada global objek, termasuk peoperti yang diwariskan, jika ada.

- -

Objek lain di lingkup global salah satunya dibuat oleh user script atau disediakan oleh aplikasi host. Objek host tersedia di konteks browser, didokumentasi di Referensi API. Untuk informasi lengkap tentang perbedaan antara DOM dan inti JavaScript, lihat Gambaran teknologi javaScript.

- -

Objek standar berdasarkan kategori

- -

Properti nilai

- -

Properti global ini mengembalikan nilai simple; tidak memiliki properti ataupun method.

- -
    -
  • {{jsxref("Global_Objects/Infinity", "Infinity")}}
  • -
  • {{jsxref("Global_Objects/NaN", "NaN")}}
  • -
  • {{jsxref("Global_Objects/undefined", "undefined")}}
  • -
  • {{jsxref("Global_Objects/null", "null")}} literal
  • -
- -

Properti fungsi

- -

Fungsi global—fungsi yang di panggil secara global bukan pada objek — langsung mengembalikan nilai ke pemenggil.

- -
    -
  • {{jsxref("Global_Objects/eval", "eval()")}}
  • -
  • {{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
  • -
  • {{jsxref("Global_Objects/isFinite", "isFinite()")}}
  • -
  • {{jsxref("Global_Objects/isNaN", "isNaN()")}}
  • -
  • {{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
  • -
  • {{jsxref("Global_Objects/parseInt", "parseInt()")}}
  • -
  • {{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
  • -
  • {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
  • -
  • {{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
  • -
  • {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
  • -
  • {{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
  • -
  • {{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
  • -
- -

Fundamental objek

- -

Ini merupakan fundamental, objek dasar berdasarkan pada semua objek lain yang didasarkan. Ini termasuk objek yang mewakili objek umum, fungsi dan error.

- -
    -
  • {{jsxref("Global_Objects/Object", "Object")}}
  • -
  • {{jsxref("Global_Objects/Function", "Function")}}
  • -
  • {{jsxref("Global_Objects/Boolean", "Boolean")}}
  • -
  • {{jsxref("Global_Objects/Symbol", "Symbol")}}
  • -
  • {{jsxref("Global_Objects/Error", "Error")}}
  • -
  • {{jsxref("Global_Objects/EvalError", "EvalError")}}
  • -
  • {{jsxref("Global_Objects/InternalError", "InternalError")}}
  • -
  • {{jsxref("Global_Objects/RangeError", "RangeError")}}
  • -
  • {{jsxref("Global_Objects/ReferenceError", "ReferenceError")}}
  • -
  • {{jsxref("Global_Objects/SyntaxError", "SyntaxError")}}
  • -
  • {{jsxref("Global_Objects/TypeError", "TypeError")}}
  • -
  • {{jsxref("Global_Objects/URIError", "URIError")}}
  • -
- -

Nomor dan tanggal

- -

Objek dasar yang mewakili angka, tanggal dan kalkulasi matematik.

- -
    -
  • {{jsxref("Global_Objects/Number", "Number")}}
  • -
  • {{jsxref("Global_Objects/Math", "Math")}}
  • -
  • {{jsxref("Global_Objects/Date", "Date")}}
  • -
- -

Pengolah teks

- -

Objek yang mewakili string dan dukungan untuk memanipulasinya.

- -
    -
  • {{jsxref("Global_Objects/String", "String")}}
  • -
  • {{jsxref("Global_Objects/RegExp", "RegExp")}}
  • -
- -

Koleksi Index

- -

Objek ini mewakili koleksi data berdasarkan nilai index. Ini termasuk (jenis) array dan konstruksi mirip array (array-like).

- -
    -
  • {{jsxref("Global_Objects/Array", "Array")}}
  • -
  • {{jsxref("Global_Objects/Int8Array", "Int8Array")}}
  • -
  • {{jsxref("Global_Objects/Uint8Array", "Uint8Array")}}
  • -
  • {{jsxref("Global_Objects/Uint8ClampedArray", "Uint8ClampedArray")}}
  • -
  • {{jsxref("Global_Objects/Int16Array", "Int16Array")}}
  • -
  • {{jsxref("Global_Objects/Uint16Array", "Uint16Array")}}
  • -
  • {{jsxref("Global_Objects/Int32Array", "Int32Array")}}
  • -
  • {{jsxref("Global_Objects/Uint32Array", "Uint32Array")}}
  • -
  • {{jsxref("Global_Objects/Float32Array", "Float32Array")}}
  • -
  • {{jsxref("Global_Objects/Float64Array", "Float64Array")}}
  • -
- -

Koleksi keyed

- -

Objek ini merupakan koleksi yang menggunakan key; mengandung unsur yang iterable di urutan penyisipan.

- -
    -
  • {{jsxref("Map")}}
  • -
  • {{jsxref("Set")}}
  • -
  • {{jsxref("WeakMap")}}
  • -
  • {{jsxref("WeakSet")}}
  • -
- -

Koleksi vektor

- -

{{Glossary("SIMD")}} tipe data vector adalah objek dimana data diatur arahnya.

- -
    -
  • {{jsxref("SIMD")}} {{experimental_inline}}
  • -
  • {{jsxref("Float32x4", "SIMD.Float32x4")}} {{experimental_inline}}
  • -
  • {{jsxref("Float64x2", "SIMD.Float64x2")}} {{experimental_inline}}
  • -
  • {{jsxref("Int8x16", "SIMD.Int8x16")}} {{experimental_inline}}
  • -
  • {{jsxref("Int16x8", "SIMD.Int16x8")}} {{experimental_inline}}
  • -
  • {{jsxref("Int32x4", "SIMD.Int32x4")}} {{experimental_inline}}
  • -
  • {{jsxref("Uint8x16", "SIMD.Uint8x16")}} {{experimental_inline}}
  • -
  • {{jsxref("Uint16x8", "SIMD.Uint16x8")}} {{experimental_inline}}
  • -
  • {{jsxref("Uint32x4", "SIMD.Uint32x4")}} {{experimental_inline}}
  • -
  • {{jsxref("Bool8x16", "SIMD.Bool8x16")}} {{experimental_inline}}
  • -
  • {{jsxref("Bool16x8", "SIMD.Bool16x8")}} {{experimental_inline}}
  • -
  • {{jsxref("Bool32x4", "SIMD.Bool32x4")}} {{experimental_inline}}
  • -
  • {{jsxref("Bool64x2", "SIMD.Bool64x2")}} {{experimental_inline}}
  • -
- -

Data terstruktur

- -

Objek ini mewakili dan berinteraksi dengan buffer data terstruktur dan data yang dikodekan menggunakan JavaScript Object Notation (JSON).

- -
    -
  • {{jsxref("ArrayBuffer")}}
  • -
  • {{jsxref("SharedArrayBuffer")}} {{experimental_inline}}
  • -
  • {{jsxref("Atomics")}} {{experimental_inline}}
  • -
  • {{jsxref("DataView")}}
  • -
  • {{jsxref("JSON")}}
  • -
- -

Kontrol objek abstraksi 

- -
    -
  • {{jsxref("Promise")}}
  • -
  • {{jsxref("Generator")}}
  • -
  • {{jsxref("GeneratorFunction")}}
  • -
- -

Refleksi (Pantulan)

- -
    -
  • {{jsxref("Reflect")}}
  • -
  • {{jsxref("Proxy")}}
  • -
- -

Internasionalisasi

- -

Penambahan inti ECMAScript untuk fungsi bahasa-sensitif.

- -
    -
  • {{jsxref("Intl")}}
  • -
  • {{jsxref("Global_Objects/Collator", "Intl.Collator")}}
  • -
  • {{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}
  • -
  • {{jsxref("Global_Objects/NumberFormat", "Intl.NumberFormat")}}
  • -
- -

Objek Non-standar

- -
    -
  • {{jsxref("Iterator")}} {{non-standard_inline}}
  • -
  • {{jsxref("ParallelArray")}} {{non-standard_inline}}
  • -
  • {{jsxref("StopIteration")}} {{non-standard_inline}}
  • -
- -

Lainnya

- - -
- -

 

diff --git a/files/id/web/javascript/reference/global_objects/isnan/index.html b/files/id/web/javascript/reference/global_objects/isnan/index.html deleted file mode 100644 index b7a6774528..0000000000 --- a/files/id/web/javascript/reference/global_objects/isnan/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: isNaN() -slug: Web/JavaScript/Reference/Global_Objects/isNaN -translation_of: Web/JavaScript/Reference/Global_Objects/isNaN ---- -
{{jsSidebar("Objects")}}
- -

Fungsi isNaN() menentukan apakah nilai adalah sebuah {{jsxref("NaN")}} atau bukan. Catatan: pemaksaan pada fungsi isNaN memiliki aturan yang menarik. Anda mungkin ingin menggunakan {{jsxref("Number.isNaN()")}}, seperti yang didefinisikan dalam ECMAScript 2015.

- -

Syntax

- -
isNaN(value)
- -

Parameters

- -
-
value
-
Nilai yang akan di uji.
-
- -

Return value

- -

true Jika nilai yang di uji adalah {{jsxref("NaN")}}; jika tidak, false.

- -

Deskripsi

- -

Kebutuhan akan fungsi isNaN

- -

Mungkin tidak seperti nilai lainnya dalam javascript, Ini tidak memungkinkan untuk mengandalkan operator persamaan (== dan ===) untuk menentukan bahwa nilai adalah {{jsxref("NaN")}} atau bukan, karena NaN == NaN dan NaN === NaN mengevaluasi ke false. Oleh karena itu, diperlukan adanya fungsi isNaN.

- -

Asal Mula Nilai NaN

- -

NilaiNaN dihasilkan saat operasi aritmatika menghasilkan nilai undefined atau unrepresentable. Nilai tersebut tidak harus mewakili kondisi overflowNaN juga dihasilkan dari percobaan pemaksaan ke nilai numerik dari nilai non-numerik yang tidak memiliki nilai numerik primitif yang tersedia.

- -

Misalnya, membagi nol dengan nol menghasilkan sebuah NaN — namun membagi angka lain dengan nol tidak menghasilkan sebuah NaN.

- -

Perilaku Khusus yang membingungkan

- -

Karena versi paling awal dari spesifikasi fungsi isNaN , perilaku untuk argumen non-numerik menjadi membingungkan. Ketika argumen ke fungsi isNaN bukan bertipe Number, Nilainya akan dipaksakan terlebih dahulu ke tipe Number. Nilai yang dihasilkan kemudian diuji untuk menentukan apakah itu {{jsxref("NaN")}}. Jadi untuk non-angka yang jika dipaksakan pada hasil numerik menghasilkan nilai numerik non-NaN (terutama string kosong dan primitif boolean, yang jika dipaksakan memberi nilai numerik nol atau satu), nilai pengembalian "false" mungkin tidak terduga; String kosong, misalnya, pastinya "not a number". Kebingungan itu berawal dari kenyataan bahwa istilah "not a number", memiliki arti khusus untuk angka yang diwakili sebagai nilai floating-point IEEE-754. Fungsi harus diinterpretasikan sebagai penjawab pertanyaan, "apakah nilai ini, jika dipaksakan pada nilai numerik, nilai IEEE-754 'Not A Number'?"

- -

Versi terbaru dari ECMAScript (ES2015) berisi fungsi {{jsxref("Number.isNaN()")}}. Number.isNaN(x) akan menjadi cara yang andal untuk menguji apakah x adalah NaN atau bukan. Bahkan dengan Number.isNaN, namun arti NaN tetap merupakan makna numerik yang tepat, dan bukan sekadar, "not a number". Sebagai alternatif, untuk ketidakhadiran Number.isNaN, ekspresi (x != x) adalah cara yang lebih dapat diandalkan untuk menguji apakah variabel x adalah NaN atau bukan, karena hasilnya tidak sesuai dengan false positive yang membuat isNaN tidak dapat diandalkan.

- -

Anda bisa memikirkan isNaN sebagai:

- -
var isNaN = function(value) {
-    return Number.isNaN(Number(value));
-}
- -

Contoh

- -
isNaN(NaN);       // true
-isNaN(undefined); // true
-isNaN({});        // true
-
-isNaN(true);      // false
-isNaN(null);      // false
-isNaN(37);        // false
-
-// strings
-isNaN('37');      // false: "37" dikonversi ke nomor 37 yang mana bukan NaN
-isNaN('37.37');   // false: "37.37" dikonversi ke nomor 37.37 yang mana bukan NaN
-isNaN('123ABC');  // true:  parseInt("123ABC") adalah 123 namun Number("123ABC") adalah NaN
-isNaN('');        // false: string kosing dikonversi ke 0 yang mana bukan NaN
-isNaN(' ');       // false: string dengan spasi dikonversi ke 0 yang mana bukan NaN
-
-// dates
-isNaN(new Date());                // false
-isNaN(new Date().toString());     // true
-
-// Ini adalah false positif dan alasan mengapa NaN tidak sepenuhnya dapat diandalkan
-isNaN('blabla');   // true: "blabla" dikonversi ke nomor.
-                   // Parsing ini sebagai nomor gagal dan mengembalikan NaN
-
- -

Berguna dalam perilaku khusus

- -

Ada cara penggunaan yang lebih berorientasi untuk memikirkan isNaN isNaN(): Jika isNaN(x) mengembalikan false, anda bisa menggunakan x dalam ekspresi aritmatika tidak membuat ekspresi mengembalikan NaN. Jika itu mengembalikantrue, x akan membuat setiap ekspresi aritmatika mengembalikan NaN. Ini berarti bahwa dalam JavaScript, isNaN(x) == true setara dengan x - 0 mengembalikan NaN (meskipun di JavaScript x - 0 == NaN selalu mengembalikan false, jadi anda tidak bisa mengujinya). Sebenarnya, isNaN(x), isNaN(x - 0), isNaN(Number(x)), Number.isNaN(x - 0), dan Number.isNaN(Number(x)) selalu kembali sama dan di JavaScriptisNaN(x) hanya bentuk sesingkat mungkin untuk mengungkapkan masing-masing istilah ini.

- -

Anda dapat menggunakan ini, misalnya, untuk menguji apakah sebuah argumen terhadap suatu fungsi secara aritmatika dapat diolah (dapat digunakan "seperti" angka), atau jika tidak dan Anda harus memberikan nilai default atau yang lainnya. Dengan cara ini Anda dapat memiliki fungsi yang memanfaatkan fleksibilitas penuh JavaScript yang disediakan oleh nilai konversi secara implisit bergantung pada konteks.

- -

Contoh

- -
function increment(x) {
-  if (isNaN(x)) x = 0;
-  return x + 1;
-}
-
-// Efek yang sama dengan Number.isNaN():
-function increment(x) {
-  if (Number.isNaN(Number(x))) x = 0;
-  return x + 1;
-}
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x)selalu salah, meski x memang bukan sebuah
-// nomor, namun bisa digunakan seperti itu dalam ekspresi
-// aritmatika
-increment('');            // 1: "" dikonversi ke 0
-increment(new String());  // 1: Objek String yang mewakili string kosong dikonversi menjadi 0
-increment([]);            // 1: [] dikonversi ke 0
-increment(new Array());   // 1: Objek array yang mewakili sebuah array kosong dikonversi menjadi 0
-increment('0');           // 1: "0" dikonversi ke 0
-increment('1');           // 2: "1" dikonversi ke 1
-increment('0.1');         // 1.1: "0.1" dikonversi ke 0.1
-increment('Infinity');    // Infinity: "Infinity" dikonversi ke Infinity
-increment(null);          // 1: null dikonversi ke 0
-increment(false);         // 1: false dikonversi ke 0
-increment(true);          // 2: true dikonversi ke 1
-increment(new Date());    // mengembalikan tanggal/waktu sekarang dalam milidetik ditambah 1
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x) selalu false dan x memang angka
-increment(-1);            // 0
-increment(-0.1);          // 0.9
-increment(0);             // 1
-increment(1);             // 2
-increment(2);             // 3
-// ... dan seterusnya ...
-increment(Infinity);      // Infinity
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x) selalu true dan x benar-benar bukan angka,
-// sehingga fungsi tersebut menggantikannya dengan 0 dan mengembalikan 1
-increment(String);            // 1
-increment(Array);             // 1
-increment('blabla');          // 1
-increment('-blabla');         // 1
-increment(0 / 0);               // 1
-increment('0 / 0');             // 1
-increment(Infinity / Infinity); // 1
-increment(NaN);               // 1
-increment(undefined);         // 1
-increment();                  // 1
-
-// isNaN(x) selalu sama dengan isNaN(Number(x)),
-// namun kehadirannya x adalah wajib disini!
-isNaN(x) == isNaN(Number(x)); // true untuk setiap nilai x, termasuk x == undefined,
-                              // karena isNaN(undefined) == true dan Number(undefined) mengembalikan NaN,
-                              // namun ...
-isNaN() == isNaN(Number());   // false, karena isNaN() == true dan Number() == 0
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.isNaN")}}

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/json/index.html b/files/id/web/javascript/reference/global_objects/json/index.html deleted file mode 100644 index 4f07030358..0000000000 --- a/files/id/web/javascript/reference/global_objects/json/index.html +++ /dev/null @@ -1,243 +0,0 @@ ---- -title: JSON -slug: Web/JavaScript/Reference/Global_Objects/JSON -translation_of: Web/JavaScript/Reference/Global_Objects/JSON ---- -
{{JSRef}}
- -

Didalam object JSON terdapat banyak method untuk memparse JavaScript Object Notation ({{glossary("JSON")}}) dan mengkonversi nilai ke JSON. Hal ini tidak dapat di gunakan atau dibangun, dan selain dari kedua sifat method tersebut tidak memiliki fungsi tersendiri.

- -

Deskripsi

- -

JavaScript Object Notation

- -

JSON merupakan sebuah syntax untuk menserialisasi objects, array, angka, string, boolean, dan {{jsxref("null")}}. Hal ini dilihat berdasarkan pada syntax  javascript. Akan tetapi terpisah dari dari hal tersebut: beberapa javascript bukanlah JSON, dan beberapa JSON juga tidak dapat dikatakan sebagai Javascript. Lihat juga JSON: The JavaScript subset that isn't.

- - - - - - - - - - - - - - - - - - - - - - - -
Perbedaan JavaScript dan JSON
Type pada JavaScriptPerbedaan dengan JSON
Object dan ArrayNama properti harus menggunakan string double quotes; tidak diakhiri dengan koma.
AngkaTidak diawali dengan nol; desimal harus di ikuti setidaknya satu digit.
String -

Hanya beberapa karakter tertentu yang menggunakan escape; Kontrol karakter tertentu tidak diperbolehkan; Pemisah baris Unicode (U+2028) dan pemisah paragraf (U+2029) dapat digunakan; string harus menggunakan double-quoted. Lihat contoh dimana {{jsxref("JSON.parse()")}} bisa digunakan dan {{jsxref("SyntaxError")}} dilemparkan ketika mengevaluasi kode sebagai javascript:

- -
-var kode = '"\u2028\u2029"';
-JSON.parse(kode); // bisa digunakan.
-eval(kode); // gagal!
-
-
- -

Syntax JSON lengkapnya sebagai berikut:

- -
JSON = null
-    or true or false
-    or JSONNumber
-    or JSONString
-    or JSONObject
-    or JSONArray
-
-JSONNumber = - PositiveNumber
-          or PositiveNumber
-PositiveNumber = DecimalNumber
-              or DecimalNumber . Digits
-              or DecimalNumber . Digits ExponentPart
-              or DecimalNumber ExponentPart
-DecimalNumber = 0
-             or OneToNine Digits
-ExponentPart = e Exponent
-            or E Exponent
-Exponent = Digits
-        or + Digits
-        or - Digits
-Digits = Digit
-      or Digits Digit
-Digit = 0 through 9
-OneToNine = 1 through 9
-
-JSONString = ""
-          or " StringCharacters "
-StringCharacters = StringCharacter
-                or StringCharacters StringCharacter
-StringCharacter = any character
-                  except " or \ or U+0000 through U+001F
-               or EscapeSequence
-EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
-              or \u HexDigit HexDigit HexDigit HexDigit
-HexDigit = 0 through 9
-        or A through F
-        or a through f
-
-JSONObject = { }
-          or { Members }
-Members = JSONString : JSON
-       or Members , JSONString : JSON
-
-JSONArray = [ ]
-         or [ ArrayElements ]
-ArrayElements = JSON
-             or ArrayElements , JSON
-
- -

Whitespace yang tidak signifikan dapat digunakan dimanasaja kecuali didalam JSONNumber (angka tidak dipisahkan dengan whitespace) atau JSONString (dimana ditafsirkan sebagai karakter yang sesuai dalam string; atau akan menyebabkan kesalahan). Karakter Tab (U+0009), carriage return (U+000D), line feed (U+000A), dan karakter spasi (U+0020) merupakan karakter whitespace yang valid.

- -

Method

- -
-
{{jsxref("JSON.parse()")}}
-
Memparse string sebagai JSON, biasanya mengubah nilai yang diberikan beserta sifatnya, dan mengembalikan nilai.
-
{{jsxref("JSON.stringify()")}}
-
Mengembalikan string JSON berdasarkan nilai spesifik, biasanya termasuk beberapa properti tertentu saja atau mengganti nilai properti secara user-defined.
-
- -

Polyfill

- -

Object JSON tidak didukung oleh browser lawas. Anda bisa menyiasatinya dengan memasukkan kode berikut di awal skrip Anda, memungkinkan penggunaan JSON objek dalam implementasi yang secara native tidak mendukung Object JSON (seperti Internet Explorer 6).

- -

Algoritma berikut adalah tiruan dari objek JSON asli:

- -
if (!window.JSON) {
-  window.JSON = {
-    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
-    stringify: (function () {
-      var toString = Object.prototype.toString;
-      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
-      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
-      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
-      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
-      return function stringify(value) {
-        if (value == null) {
-          return 'null';
-        } else if (typeof value === 'number') {
-          return isFinite(value) ? value.toString() : 'null';
-        } else if (typeof value === 'boolean') {
-          return value.toString();
-        } else if (typeof value === 'object') {
-          if (typeof value.toJSON === 'function') {
-            return stringify(value.toJSON());
-          } else if (isArray(value)) {
-            var res = '[';
-            for (var i = 0; i < value.length; i++)
-              res += (i ? ', ' : '') + stringify(value[i]);
-            return res + ']';
-          } else if (toString.call(value) === '[object Object]') {
-            var tmp = [];
-            for (var k in value) {
-              if (value.hasOwnProperty(k))
-                tmp.push(stringify(k) + ': ' + stringify(value[k]));
-            }
-            return '{' + tmp.join(', ') + '}';
-          }
-        }
-        return '"' + value.toString().replace(escRE, escFunc) + '"';
-      };
-    })()
-  };
-}
-
- -

Lebih kompleks dari polyfills yang banyak dikenal untuk object JSON adalah JSON2 dan JSON3.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/json/parse/index.html b/files/id/web/javascript/reference/global_objects/json/parse/index.html deleted file mode 100644 index 5eb3f60424..0000000000 --- a/files/id/web/javascript/reference/global_objects/json/parse/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: JSON.parse() -slug: Web/JavaScript/Reference/Global_Objects/JSON/parse -tags: - - ECMAScript5 - - JSON - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse ---- -
{{JSRef}}
- -

Method JSON.parse() memparse string ke JSON, biasanya mengubah nilai yang dihasilkan oleh parsing.

- -

Sintaks

- -
JSON.parse(text[, reviver])
- -

Parameters

- -
-
text
-
String yang akan di parse ke JSON. Lihat objek {{jsxref("JSON")}} untuk deskripsi lengkap sintaks JSON.
-
reviver {{optional_inline}}
-
Jika sebuah fungsi, mendeskripsikan bagaimana nilai asli dihasilkan oleh parsing berubah, sebelum dikembalikan.
-
- -

Pemulangan

- -

Mengembalikan {{jsxref("Object")}} sesuai dengan teks JSON yang diberikan.

- -

Lontaran

- -

Melontarkan pengecualian {{jsxref("SyntaxError")}} jika string yang di parse tidak sesuai JSON.

- -

Contoh

- -

Menggunakan JSON.parse()

- -
JSON.parse('{}');              // {}
-JSON.parse('true');            // true
-JSON.parse('"foo"');           // "foo"
-JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
-JSON.parse('null');            // null
-
- -

Menggunakan parameter reviver

- -

Jika reviver telah ditentukan, nilai dihitung dengan parsing transformed sebelum dikembalikan. Khususnya, nilai yang terhitung, dan semua propertinya (dimulai dari properti yang paling bersarang dan berlanjut ke nilai asli), secara individu dijalankan melalui reviver, yang di panggil dengan objek yang berada di dalam properti yang akan diproses sebagai this dan dengan nama properti sebagai string dan nilai properti sebagai argumen. jika fungsi reviver mengembalikan {{jsxref("undefined")}} (tidak mengembalikan nilai, contoh, jika eksekusi gagal di akhir fungsi), properti akan dihapus dari objek. Jika tidak, properti akan didefinisikan ulang sebagai sebuah nilai kembali.

- -

reviver dipanggil dengan string kosong dan nilai paling atas mengizinkan tranformsi dari nilai paling atas. Jadi untuk menangani kasus ini dengan baik, biasanya dengan mengembalikan nilai yang diberikan, atau JSON.parse() akan mengembalikan {{jsxref("undefined")}}.

- -
JSON.parse('{"p": 5}', function(k, v) {
-  if (k === '') { return v; } // if topmost value, return it,
-  return v * 2;               // else return v * 2.
-});                           // { p: 10 }
-
-JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) {
-  console.log(k); // log the current property name, the last is "".
-  return v;       // return the unchanged property value.
-});
-
-// 1
-// 2
-// 4
-// 6
-// 5
-// 3
-// ""
-
- -

JSON.parse() tidak mengizinkan trailing koma

- -
// both will throw a SyntaxError
-JSON.parse('[1, 2, 3, 4, ]');
-JSON.parse('{"foo" : 1, }');
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Gecko-specific notes

- -

Pada Gecko 29 {{geckoRelease("29")}}, string JSON yang gagal akan menampilkan pesan kesalahan yang lebih rinci tentang error dalam memparse. Hal ini sangat berguna ketika mendebug data JSON yang besar.

- -
JSON.parse('[1, 2, 3, 4,]');
-// SyntaxError: JSON.parse: unexpected character at
-// line 1 column 13 of the JSON data
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/clear/index.html b/files/id/web/javascript/reference/global_objects/map/clear/index.html deleted file mode 100644 index 2869835e02..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/clear/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: Map.prototype.clear() -slug: Web/JavaScript/Reference/Global_Objects/Map/clear -translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear ---- -
{{JSRef}}
- -

Method clear() menghapus semua elemen yang ada pada objek Map.

- -

Sintaks

- -
myMap.clear();
- -

Contoh

- -

Menggunakan method clear

- -
var myMap = new Map();
-myMap.set("bar", "baz");
-myMap.set(1, "foo");
-
-myMap.size;       // 2
-myMap.has("bar"); // true
-
-myMap.clear();
-
-myMap.size;       // 0
-myMap.has("bar")  // false
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar38{{CompatGeckoDesktop("19.0")}}11257.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasart{{CompatNo}}38{{CompatGeckoMobile("19.0")}}{{CompatNo}}{{CompatNo}}8
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/delete/index.html b/files/id/web/javascript/reference/global_objects/map/delete/index.html deleted file mode 100644 index ad9d1922b9..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/delete/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Map.prototype.delete() -slug: Web/JavaScript/Reference/Global_Objects/Map/delete -translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete ---- -
{{JSRef}}
- -

Method  delete() menghapus elemen yang ditentukan dari objek Map.

- -

Sintaks

- -
myMap.delete(key);
- -

Parameter

- -
-
key
-
Diperlukan. Kunci dari elemen untuk menghapusnya dari objek Map.
-
- -

Return value

- -

Mengembalikan nilai true jika elemen yang ada di dalam objek Map ada dan telah dihapus, atau false jika elemen tidak ada.

- -

Contoh

- -

Menggunakan method delete

- -
var myMap = new Map();
-myMap.set("bar", "foo");
-
-myMap.delete("bar"); // Returns true. Berhasil dihapus.
-myMap.has("bar");    // Returns false. Elemen "bar" sudah tidak tersedia.
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar38{{CompatGeckoDesktop("13.0")}}11257.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}38{{CompatGeckoMobile("13.0")}}{{CompatNo}}{{CompatNo}}8
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/index.html b/files/id/web/javascript/reference/global_objects/map/index.html deleted file mode 100644 index 9e4a93cfa0..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/index.html +++ /dev/null @@ -1,443 +0,0 @@ ---- -title: Map -slug: Web/JavaScript/Reference/Global_Objects/Map -tags: - - ECMAScript6 - - JavaScript - - Map - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Map ---- -
{{JSRef}}
- -

The Map object is a simple key/value map. Any value (both objects and {{Glossary("Primitive", "primitive values")}}) may be used as either a key or a value.

- -

Syntax

- -
new Map([iterable])
-
- -

Parameters

- -
-
iterable
-
Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair is added to the new Map. null is treated as undefined.
-
- -

Description

- -

A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of [key, value] for each iteration.

- -

Key equality

- -

Key equality is based on the "same-value" algorithm: NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. In earlier versions of the ECMAScript 6 draft -0 and +0 were considered distinct (even though -0 === +0), this has been changed in later versions and has been adapted in Gecko 29 {{geckoRelease("29")}} ({{bug("952870")}}) and a recent nightly Chrome.

- -

Objects and maps compared

- -

{{jsxref("Object", "Objects")}} are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better:

- - - -

This does not mean you should use Maps everywhere, objects still are used in most cases. Map instances are only useful for collections, and you should consider adapting your code where you have previously used objects for such. Objects shall be used as records, with fields and methods.
- If you're still not sure which one to use, ask yourself the following questions:

- - - -

Those all are signs that you want a Map for a collection. If in contrast you have a fixed amount of keys, operate on them individually, and distinguish between their usage, then you want an object.

- -

Properties

- -
-
Map.length
-
The value of the length property is 0.
-
{{jsxref("Map.@@species", "get Map[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Map.prototype")}}
-
Represents the prototype for the Map constructor. Allows the addition of properties to all Map objects.
-
- -

Map instances

- -

All Map instances inherit from {{jsxref("Map.prototype")}}.

- -

Properties

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}

- -

Methods

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

- -

Examples

- -

Using the Map object

- -
var myMap = new Map();
-
-var keyString = "a string",
-    keyObj = {},
-    keyFunc = function () {};
-
-// setting the values
-myMap.set(keyString, "value associated with 'a string'");
-myMap.set(keyObj, "value associated with keyObj");
-myMap.set(keyFunc, "value associated with keyFunc");
-
-myMap.size; // 3
-
-// getting the values
-myMap.get(keyString);    // "value associated with 'a string'"
-myMap.get(keyObj);       // "value associated with keyObj"
-myMap.get(keyFunc);      // "value associated with keyFunc"
-
-myMap.get("a string");   // "value associated with 'a string'"
-                         // because keyString === 'a string'
-myMap.get({});           // undefined, because keyObj !== {}
-myMap.get(function() {}) // undefined, because keyFunc !== function () {}
-
- -

Using NaN as Map keys

- -

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works, because NaNs are indistinguishable from each other:

- -
var myMap = new Map();
-myMap.set(NaN, "not a number");
-
-myMap.get(NaN); // "not a number"
-
-var otherNaN = Number("foo");
-myMap.get(otherNaN); // "not a number"
-
- -

Iterating Maps with for..of

- -

Maps can be iterated using a for..of loop:

- -
var myMap = new Map();
-myMap.set(0, "zero");
-myMap.set(1, "one");
-for (var [key, value] of myMap) {
-  console.log(key + " = " + value);
-}
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
-for (var key of myMap.keys()) {
-  console.log(key);
-}
-// Will show 2 logs; first with "0" and second with "1"
-
-for (var value of myMap.values()) {
-  console.log(value);
-}
-// Will show 2 logs; first with "zero" and second with "one"
-
-for (var [key, value] of myMap.entries()) {
-  console.log(key + " = " + value);
-}
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
- -

Iterating Maps with forEach()

- -

Maps can be iterated using the forEach() method:

- -
myMap.forEach(function(value, key) {
-  console.log(key + " = " + value);
-}, myMap)
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
- -

Relation with Array objects

- -
var kvArray = [["key1", "value1"], ["key2", "value2"]];
-
-// Use the regular Map constructor to transform a 2D key-value Array into a map
-var myMap = new Map(kvArray);
-
-myMap.get("key1"); // returns "value1"
-
-// Use the spread operator to transform a map into a 2D key-value Array.
-console.log(uneval([...myMap])); // Will show you exactly the same Array as kvArray
-
-// Or use the spread operator on the keys or values iterator to get
-// an array of only the keys or values
-console.log(uneval([...myMap.keys()])); // Will show ["key1", "key2"]
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-map-objects', 'Map')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support -

{{ CompatChrome(38) }} [1]

-
{{ CompatGeckoDesktop("13") }}11257.1
Constructor argument: new Map(iterable){{ CompatChrome(38) }}{{ CompatGeckoDesktop("13") }}{{CompatNo}}25{{CompatNo}}
iterable{{ CompatChrome(38) }}{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Map.clear(){{ CompatChrome(31) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("19")}}11257.1
Map.keys(), Map.values(), Map.entries(){{ CompatChrome(37) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("20")}}{{CompatNo}}257.1
Map.forEach(){{ CompatChrome(36) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("25")}}11257.1
Key equality for -0 and 0{{ CompatChrome(34) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatNo}}
Constructor argument: new Map(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{ CompatGeckoDesktop("42") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatChrome(38) }} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Map(iterable){{CompatNo}}{{ CompatChrome(38) }}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Map.clear(){{CompatNo}}{{ CompatChrome(31) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Map.keys(), Map.values(), Map.entries(){{CompatNo}}{{ CompatChrome(37) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("20")}}{{CompatNo}}{{CompatNo}}8
Map.forEach(){{CompatNo}}{{ CompatChrome(36) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Key equality for -0 and 0{{CompatNo}}{{ CompatChrome(34) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Constructor argument: new Map(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Starting with Chrome 31, the feature was available behind a preference. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/math/abs/index.html b/files/id/web/javascript/reference/global_objects/math/abs/index.html deleted file mode 100644 index c15b00b315..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/abs/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Math.abs() -slug: Web/JavaScript/Reference/Global_Objects/Math/abs -tags: - - Math - - abs - - math abs -translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs ---- -
{{JSRef}}
- -

Fungsi Math.abs() mengembalikan nilai mutlak dari sebuah bilangan, yakni

- -

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases}

- -

Sintak

- -
Math.abs(x)
- -

Parameter

- -
-
x
-
Sebuah bilangan.
-
- -

Nilai kembali

- -

Nilai mutlak dari bilangan yang diberikan.

- -

Deskripsi

- -

Karena abs() merupakan sebuah metode statis dari Math, anda harus menggunakannya/menulisnya sebagai berikut Math.abs(), Bukan sebagai metode dari sebuah object Math yang anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Prilaku dari Math.abs()

- -

Mengabaikan objek kosong, sebuah array dengan lebih dari satu anggota, sebuah string non-numerik atau {{jsxref("undefined")}}/variabel kosong dikembalikan{{jsxref("NaN")}}. Mengabaikan {{jsxref("null")}}, sebuah string kosong atau sebuah array kosong akan menghasilkan 0.

- -
Math.abs('-1');     // 1
-Math.abs(-2);       // 2
-Math.abs(null);     // 0
-Math.abs('');       // 0
-Math.abs([]);       // 0
-Math.abs([2]);      // 2
-Math.abs([1,2]);    // NaN
-Math.abs({});       // NaN
-Math.abs('string'); // NaN
-Math.abs();         // NaN
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan pada JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome untuk AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/ceil/index.html b/files/id/web/javascript/reference/global_objects/math/ceil/index.html deleted file mode 100644 index cba010ffdb..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/ceil/index.html +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: Math.ceil() -slug: Web/JavaScript/Reference/Global_Objects/Math/ceil -tags: - - JavaScript - - Math - - Metode - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil ---- -
{{JSRef}}
- -

Fungsi Math.ceil() adalah memberikan nilai integer lebih-besar-dari terkecil atau sama-dengan (pembulatan ke atas) nilai yang ditentukan.

- -

Catatan: Nilai kembalian Math.ceil(null) adalah integer 0 dan tidak memberikan kesalahan NaN.

- -
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
- - - -

Sintaks

- -
Math.ceil(x)
- -

Parameter

- -
-
x
-
Sebuah angka.
-
- -

Nilai kembali

- -

Nilai integer lebih-besar-dari terkecil atau sama-dengan (pembulatan ke atas) nilai yang ditentukan.

- -

Deskripsi

- -

Karena ceil() adalah sebuah metode statis dari Math, Anda harus selalu menggunakan sebagai Math.ceil(), bukan sebagai metode dari object  Math yang Anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Menggunakan Math.ceil()

- -

Berikut adalah contoh penggunaan dari Math.ceil().

- -
Math.ceil(.95);    // 1
-Math.ceil(4);      // 4
-Math.ceil(7.004);  // 8
-Math.ceil(-0.95);  // -0
-Math.ceil(-4);     // -4
-Math.ceil(-7.004); // -7
-
- -

Penyesuaian desimal

- -
// Closure
-(function() {
-  /**
-   * Penyesuaian desimal dari sebuah angka.
-   *
-   * @param {String}  type  Tipe dari penyesuaian.
-   * @param {Number}  value Angka.
-   * @param {Integer} exp   Eksponen (10 logaritma basis penyesuaian).
-   * @returns {Number} Nilai yang di sesuaikan.
-   */
-  function decimalAdjust(type, value, exp) {
-    // jika exp adalah undefined atau nol...
-    if (typeof exp === 'undefined' || +exp === 0) {
-      return Math[type](value);
-    }
-    value = +value;
-    exp = +exp;
-    // Jika nilai adalah bukan sebuah angka atau bilangan integer...
-    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
-      return NaN;
-    }
-    // Shift
-    value = value.toString().split('e');
-    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
-    // Shift back
-    value = value.toString().split('e');
-    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
-  }
-
-  // Decimal round
-  if (!Math.round10) {
-    Math.round10 = function(value, exp) {
-      return decimalAdjust('round', value, exp);
-    };
-  }
-  // Decimal floor
-  if (!Math.floor10) {
-    Math.floor10 = function(value, exp) {
-      return decimalAdjust('floor', value, exp);
-    };
-  }
-  // Decimal ceil
-  if (!Math.ceil10) {
-    Math.ceil10 = function(value, exp) {
-      return decimalAdjust('ceil', value, exp);
-    };
-  }
-})();
-
-// Round
-Math.round10(55.55, -1);   // 55.6
-Math.round10(55.549, -1);  // 55.5
-Math.round10(55, 1);       // 60
-Math.round10(54.9, 1);     // 50
-Math.round10(-55.55, -1);  // -55.5
-Math.round10(-55.551, -1); // -55.6
-Math.round10(-55, 1);      // -50
-Math.round10(-55.1, 1);    // -60
-// Floor
-Math.floor10(55.59, -1);   // 55.5
-Math.floor10(59, 1);       // 50
-Math.floor10(-55.51, -1);  // -55.6
-Math.floor10(-51, 1);      // -60
-// Ceil
-Math.ceil10(55.51, -1);    // 55.6
-Math.ceil10(51, 1);        // 60
-Math.ceil10(-55.59, -1);   // -55.5
-Math.ceil10(-59, 1);       // -50
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomen
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan dalam JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- -
- -
- -

{{Compat("javascript.builtins.Math.ceil")}}

- -

Lihat pula

- - diff --git a/files/id/web/javascript/reference/global_objects/math/e/index.html b/files/id/web/javascript/reference/global_objects/math/e/index.html deleted file mode 100644 index 79e9f21f4a..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/e/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Math.E -slug: Web/JavaScript/Reference/Global_Objects/Math/E -translation_of: Web/JavaScript/Reference/Global_Objects/Math/E ---- -
{{JSRef}}
- -

Properti Math.E mewakili dasar logaritma alami, e,  mendekati 2.718.

- -

Math.E=e2.718\mathtt{\mi{Math.E}} = e \approx 2.718

- -
{{EmbedInteractiveExample("pages/js/math-e.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Deskripsi

- -

Karena E adalah sebuah properti matematika statis, saudara selalu menggunakannya sebagai Math.E, daripada sebagai sebuah properti dari objek matematika yang saudara buat. (Math bukan sebuah konstruktor).

- -

Contoh

- -

Menggunakan Math.E

- -

Fungsi berikut menampilkan nilai e:

- -
function getNapier() {
-  return Math.E;
-}
-
-getNapier(); // 2.718281828459045
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}} -

definisi inisial. Diimplementasikan dalam  JavaScript 1.0.

-
{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.e', 'Math.E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- - - -

{{Compat("javascript.builtins.Math.E")}}

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/floor/index.html b/files/id/web/javascript/reference/global_objects/math/floor/index.html deleted file mode 100644 index ecd6e89cdd..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/floor/index.html +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Math.floor() -slug: Web/JavaScript/Reference/Global_Objects/Math/floor -tags: - - Math - - math floor - - pembulatan - - pembulatan bilangan - - pembulatan kebawah javascript -translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor ---- -
{{JSRef}}
- -

Fungsi Math.floor() mengembalikan bilangan bulat terbesar yang kurang dari atau sama dengan bilangan yang diberikan.

- -

Sintaks

- -
Math.floor(x)
- -

Parameter

- -
-
x
-
Sebuah bilangan.
-
- -

Nilai kembali

- -

Sebuah bilangan yang merepresentasikan bilangan bulat terbesar yang kurang dari atau sama dengan nilai yang diberikan

- -

Deskripsi

- -

Karena floor() adalah sebuah metode statis dari Math, sintaks yang harus anda gunakan adalah Math.floor(), bukan sebagai metode dari obyek Math yang anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Penggunaan Math.floor()

- -
Math.floor( 45.95); //  45
-Math.floor( 45.05); //  45
-Math.floor(  4   ); //   4
-Math.floor(-45.05); // -46
-Math.floor(-45.95); // -46
-
- -

Penyesuaian desimal

- -
// Closure
-(function() {
-  /**
-   * Penyesuaian desimal dari sebuah bilangan.
-   *
-   * @param {String}  type  Jenis penyesuaian.
-   * @param {Number}  value Nomor.
-   * @param {Integer} exp   Eksponen (10 logaritma dari penyesuaian dasar).
-   * @returns {Number} Nilai yang disesuaikan.
-   */
-  function decimalAdjust(jenis, nilai, eks) {
-    // Jika eks adalah undefined(belum didefinisikan) atau kosong...
-    if (typeof eks === 'undefined' || +eks === 0) {
-      return Math[jenis](nilai);
-    }
-    nilai = +nilai;
-    eks= +eks;
-    // Jika nilai bukan sebuah angka atau eks bukan sebuah bilangan integer...
-    if (isNaN(nilai) || !(typeof eks === 'number' && eks % 1 === 0)) {
-      return NaN;
-    }
-    // Pengalihan
-    nilai = nilai.toString().split('e');
-    nilai = Math[jenis](+(nilai[0] + 'e' + (nilai[1] ? (+nilai[1] - eks) : -eks)));
-    // pengalihan kembali
-    nilai = nilai.toString().split('e');
-    return +(nilai[0] + 'e' + (nilai[1] ? (+nilai[1] + eks) : eks));
-  }
-
-  // Desimal bulat
-  if (!Math.round10) {
-    Math.round10 = function(nilai, eks) {
-      return decimalAdjust('round', nilai, eks);
-    };
-  }
-  // Desimal floor
-  if (!Math.floor10) {
-    Math.floor10 = function(nilai, eks) {
-      return decimalAdjust('floor', nilai, eks);
-    };
-  }
-  // Desimal ceil
-  if (!Math.ceil10) {
-    Math.ceil10 = function(nilai, eks) {
-      return decimalAdjust('ceil', nilai, eks);
-    };
-  }
-})();
-
-// Round
-Math.round10(55.55, -1);   // 55.6
-Math.round10(55.549, -1);  // 55.5
-Math.round10(55, 1);       // 60
-Math.round10(54.9, 1);     // 50
-Math.round10(-55.55, -1);  // -55.5
-Math.round10(-55.551, -1); // -55.6
-Math.round10(-55, 1);      // -50
-Math.round10(-55.1, 1);    // -60
-// Floor
-Math.floor10(55.59, -1);   // 55.5
-Math.floor10(59, 1);       // 50
-Math.floor10(-55.51, -1);  // -55.6
-Math.floor10(-51, 1);      // -60
-// Ceil
-Math.ceil10(55.51, -1);    // 55.6
-Math.ceil10(51, 1);        // 60
-Math.ceil10(-55.59, -1);   // -55.5
-Math.ceil10(-59, 1);       // -50
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan pada JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/index.html b/files/id/web/javascript/reference/global_objects/math/index.html deleted file mode 100644 index 4d9bb6a9bb..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Math -slug: Web/JavaScript/Reference/Global_Objects/Math -tags: - - JavaScript - - Math - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Math ---- -
{{JSRef}}
- -

Math merupakan objek built-in yang memiliki properti dan method untuk perhitungan konstan dan fungsi. bukan Fungsi Objek.

- -

Description

- -

Tidak seperti global objects lain, Math bukanlah constructor. Semua properti dan method dari Math adalah static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.

- -

Properties

- -
-
{{jsxref("Math.E")}}
-
Euler's constant and the base of natural logarithms, approximately 2.718.
-
{{jsxref("Math.LN2")}}
-
Natural logarithm of 2, approximately 0.693.
-
{{jsxref("Math.LN10")}}
-
Natural logarithm of 10, approximately 2.303.
-
{{jsxref("Math.LOG2E")}}
-
Base 2 logarithm of E, approximately 1.443.
-
{{jsxref("Math.LOG10E")}}
-
Base 10 logarithm of E, approximately 0.434.
-
{{jsxref("Math.PI")}}
-
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
-
{{jsxref("Math.SQRT1_2")}}
-
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
-
{{jsxref("Math.SQRT2")}}
-
Square root of 2, approximately 1.414.
-
- -

Method

- -
-

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

-
- -
-

Note that a lot of the math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

-
- -
-
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
-
Returns the absolute value of a number.
-
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
-
Returns the arccosine of a number.
-
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
-
Returns the hyperbolic arccosine of a number.
-
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
-
Returns the arcsine of a number.
-
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
-
Returns the hyperbolic arcsine of a number.
-
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
-
Returns the arctangent of a number.
-
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
-
Returns the hyperbolic arctangent of a number.
-
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
-
Returns the arctangent of the quotient of its arguments.
-
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
-
Returns the cube root of a number.
-
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
-
Returns the smallest integer greater than or equal to a number.
-
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
-
Returns the number of leading zeroes of a 32-bit integer.
-
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
-
Returns the cosine of a number.
-
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
-
Returns the hyperbolic cosine of a number.
-
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
-
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
-
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
-
Returns subtracting 1 from exp(x).
-
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
-
Returns the largest integer less than or equal to a number.
-
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
-
Returns the nearest single precision float representation of a number.
-
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
-
Returns the square root of the sum of squares of its arguments.
-
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
-
Returns the result of a 32-bit integer multiplication.
-
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
-
Returns the natural logarithm (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
-
Returns the natural logarithm of 1 + x (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
-
Returns the base 10 logarithm of a number.
-
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
-
Returns the base 2 logarithm of a number.
-
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
-
Returns the largest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
-
Returns the smallest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
-
Returns base to the exponent power, that is, baseexponent.
-
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
-
Returns a pseudo-random number between 0 and 1.
-
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
-
Returns the value of a number rounded to the nearest integer.
-
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
-
Returns the sign of the x, indicating whether x is positive, negative or zero.
-
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
-
Returns the sine of a number.
-
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
-
Returns the hyperbolic sine of a number.
-
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
-
Returns the positive square root of a number.
-
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
-
Returns the tangent of a number.
-
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
-
Returns the hyperbolic tangent of a number.
-
Math.toSource() {{non-standard_inline}}
-
Returns the string "Math".
-
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
-
Returns the integral part of the number x, removing any fractional digits.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/math/ln10/index.html b/files/id/web/javascript/reference/global_objects/math/ln10/index.html deleted file mode 100644 index 04e4fe5468..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/ln10/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Math.LN10 -slug: Web/JavaScript/Reference/Global_Objects/Math/LN10 -translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN10 ---- -
{{JSRef}}
- -

Properti Math.LN10 mewakili logaritma alami dari 10, mendekati 2.302:

- -

Math.LN10=ln(10)2.302\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302

- -
{{EmbedInteractiveExample("pages/js/math-ln10.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Deskripsi

- -

Karena LN10 adalah sebuah properti matematika statis, saudara selalu menggunakannya sebagai Math.LN10, daripada sebagai sebuah properti objek matematika yang saudara buat (Math bukan sebuah konstruktor).

- -

Contoh

- -

-

Menggunakan Math.LN10

-

- -

Fungsi berikut menampilkan log alami dari 10:

- -
function getNatLog10() {
-  return Math.LN10;
-}
-
-getNatLog10(); // 2.302585092994046
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecisifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi inisial. Diimplementasikan di JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.2', 'Math.LN10')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- - - -

{{Compat("javascript.builtins.Math.LN10")}}

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/max/index.html b/files/id/web/javascript/reference/global_objects/math/max/index.html deleted file mode 100644 index aeb1b207ce..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/max/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Math.max() -slug: Web/JavaScript/Reference/Global_Objects/Math/max -tags: - - JavaScript - - Math - - Method - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Math/max ---- -
{{JSRef}}
- -

Fungsi Math.max() mengembalikan nilai terbesar dari zero atau lebih besar.

- -

Sintaks

- -
Math.max([value1[, value2[, ...]]])
- -

Parameter

- -
-
value1, value2, ...
-
Nomor.
-
- -

Deskripsi

- -

Karena max() merupakan method static dari Math, anda perlu menggunakan Math.max(), daripada sebagai method dari objek Math yang anda buat (Math bukan constructor).

- -

Jika tidak diberi argumen, hasilnya akan -{{jsxref("Infinity")}}.

- -

Jika setidaknya satu argumen tidak dapat dikonversi ke angka, maka hasilnya {{jsxref("NaN")}}.

- -

Contoh

- -

Penggunaan Math.max()

- -
Math.max(10, 20);   //  20
-Math.max(-10, -20); // -10
-Math.max(-10, 20);  //  20
-
- -

Pada contoh menggunakan fungsi {{jsxref("Function.prototype.apply()")}} untuk mencari nilai elemen maksimum pada sebuah numeric array. getMaxOfArray([1, 2, 3]) sama halnya dengan Math.max(1, 2, 3), tapi anda bisa menggunakan getMaxOfArray() pada programmatikal pembuatan array untuk semua ukuran.

- -
function getMaxOfArray(numArray) {
-  return Math.max.apply(null, numArray);
-}
-
- -

Atau dengan {{jsxref("Operators/Spread_operator", "spread operator")}} baru, mencari nilai terbesar menjadi lebih mudah.

- -
var arr = [1, 2, 3];
-var max = Math.max(...arr);
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/min/index.html b/files/id/web/javascript/reference/global_objects/math/min/index.html deleted file mode 100644 index eb557f36bf..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/min/index.html +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Math.min() -slug: Web/JavaScript/Reference/Global_Objects/Math/min -tags: - - JavaScript - - Math - - Method - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Math/min ---- -
{{JSRef}}
- -

Function Math.min() mengembalikan nilai terkecil dari zero atau lebih kecil.

- -

Sintaks

- -
Math.min([value1[, value2[, ...]]])
- -

Parameter

- -
-
value1, value2, ...
-
Nomor.
-
- -

Deskripsi

- -

Karena min() merupakan static method dari Math, anda perlu menggunakan  Math.min(), daripada sebagai method dari objek Math yang anda buat (Math bukanlah konstruktor).

- -

Jika tidak diberi argumen, hasilnya adalah {{jsxref("Infinity")}}.

- -

Jika setidaknya satu argumen tidak bisa di konversi ke angka, maka hasilnya{{jsxref("NaN")}}.

- -

Contoh

- -

Menggunakan Math.min()

- -

Mencari nilai terkecil diantara x dan y dan menyimpannya di variabel z:

- -
var x = 10, y = -20;
-var z = Math.min(x, y);
-
- -

Mengambil nilai dengan Math.min()

- -

Math.min() biasa digunakan untuk mengambil nilai yang terkecil atau sama berdasarkan batasan yang ada. contoh sebagai berikut.

- -
var x = f(foo);
-
-if (x > boundary) {
-  x = boundary;
-}
-
- -

bisa ditulis sebagai berikut

- -
var x = Math.min(f(foo), boundary);
-
- -

{{jsxref("Math.max()")}} bisa digunakan sama halnya denga mengambil nilai pada setiap batasan.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.min', 'Math.min')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/pow/index.html b/files/id/web/javascript/reference/global_objects/math/pow/index.html deleted file mode 100644 index 878fde0e04..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/pow/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Math.pow -slug: Web/JavaScript/Reference/Global_Objects/Math/pow -translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow ---- -

Ringkasan

-

Mengembalikan bilangan terhadap Pangkat exponent,  yaitu, bilanganeksponen.

- - - - - - - - - - - - - - - - -
Method dari Math
Diimplementasikan padaJavaScript 1.0
Edisi ECMAScriptECMAScript 1st Edition
-

Sintaks

-
Math.pow(bilangan, eksponen) 
-

Parameter

-
-
- bilangan
-
- Bilangan pokok.
-
- eksponen
-
- Eksponen yang digunakan untuk memangkatkan bilangan pokok.
-
-

Deskripsi

-

Karena pow adalah sebuah static method dari Math, anda senantiasa menggunakannya sebagai Math.pow(), daripada sebagai sebuah method dari sebuah Objek Math yang anda buat.

-

Contoh

-

Contoh: Penggunaan Math.pow

-
function raisePower(x,y) {
-   return Math.pow(x,y)
-}
-

Jika x adalah 7 dan y adalah 2, raisePower mengembalikan 49 (7 dipangkatkan 2).

-

Lihat juga

- diff --git a/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html deleted file mode 100644 index 6ac06ec718..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Object.getPrototypeOf() -slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf -translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf ---- -
{{JSRef}}
- -

Metode Object.getPrototypeOf() mengembalikan nilai prototipe dari obyek yang disebutkan (misalnya,  nilai dari properti internal [[Prototype]]).

- -

Sintaks

- -
Object.getPrototypeOf(obj)
- -

Parameter

- -
-
obj
-
Obyek yang memiliki prototipe.
-
- -

Nilai kembali

- -

Prototipe dari obyek yang diberikan. Jika tidak ada property yang ditemukan, {{jsxref("null")}} yang akan dikembalikan.

- -

Contoh

- -
var proto = {};
-var obj = Object.create(proto);
-Object.getPrototypeOf(obj) === proto; // true
-
- -

Catatan

- -

Dalam ES5, akan melemparkan eksepsi {{jsxref("TypeError")}} jika parameter obj parameter bukanlah sebuah obyek. Dalam ES6, parameter akan dipaksa menjadi {{jsxref("Object")}}.

- -
Object.getPrototypeOf("foo");
-// TypeError: "foo" is not an object (ES5 code)
-Object.getPrototypeOf("foo");
-// String.prototype                  (ES6 code)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Definisi awal.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas perambah

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Catatan khusus Opera

- -

Meskipun Opera dengan versi yang lebih lama belum mendukung Object.getPrototypeOf(), Opera mendukung properti non-standar {{jsxref("Object.proto", "__proto__")}} sejak Opera 10.50.

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/object/index.html b/files/id/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index cc79ab6890..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: Object -slug: Web/JavaScript/Reference/Global_Objects/Object -tags: - - Constructor - - JavaScript - - Object - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Object ---- -
{{JSRef}}
- -

Konstruktor Object membuat sebuah pembungkus objek.

- -

Sintaks

- -
// Persiapan literasi objek
-{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
-
-// Panggil konstruktor
-new Object([value])
- -

Parameter

- -
-
nameValuePair1, nameValuePair2, ... nameValuePairN
-
Pasangan dari nama (strings) dan nilai dimana nama dipisahkan dari nilai menggunakan titik dua (colon).
-
value
-
Nilai bebas.
-
- -

Keterangan

- -

Konstruktor Object membuat sebuah pembungkus objek dari nilai yang diberikan. Jika nilainya {{jsxref("null")}} atau {{jsxref("undefined")}}, maka akan menghasilkan dan mengembalikan objek kosong. Sebaliknya, akan mengembalikan sebuah objek dari Type yang bergantung pada nilai yang diberikan. Jika nilai adalah objek, maka nilai akan langsung dikembalikan.

- -

Ketika memanggil konteks non-constructor, Object berperilaku seperti layaknya new Object().

- -

Lihat juga object initializer / literal syntax.

- -

Properti dari konstruktor Object

- -
-
Object.length
-
Bernilai 1.
-
{{jsxref("Object.prototype")}}
-
Memungkinkan untuk menambahkan properti ke semua objek dari type Object.
-
- -

Method dari konstruktor Object

- -
-
{{jsxref("Object.assign()")}}
-
Membuat objek baru dengan menyalin nilai dari semua properti enumerable dari satu atau lebih sumber ke sebuah objek target.
-
{{jsxref("Object.create()")}}
-
Membuat objek baru dengan prototype dan properti objek tertentu.
-
{{jsxref("Object.defineProperty()")}}
-
Menambahkan nama properti berdasarkan deskripsi yang diberikan oleh descriptor pada sebuah objek.
-
{{jsxref("Object.defineProperties()")}}
-
Menambahkan nama properti yang dideskripsikan descriptors pada sebuah object.
-
{{jsxref("Object.entries()")}} {{experimental_inline}}
-
Mengembalikan sebuah array dari enumerable objek dengan  pasangan properti [key, value].
-
{{jsxref("Object.freeze()")}}
-
Membekukan objek: kode lain tidak dapat dihapus atau diubah oleh semua properti.
-
{{jsxref("Object.getOwnPropertyDescriptor()")}}
-
Mengembalikan sebuah properti descriptor untuk nama propeti pada sebuah object.
-
{{jsxref("Object.getOwnPropertyNames()")}}
-
Mengembalikan array berisi nama dari semua objek yang diberikan own enumerable dan properti non-enumerable.
-
{{jsxref("Object.getOwnPropertySymbols()")}}
-
Mengembalikan sebuah array dari semua properti simbol yang ditemukan secara langsung atas objek yang diberikan.
-
{{jsxref("Object.getPrototypeOf()")}}
-
Mengembalikan prototype dari objek tertentu.
-
{{jsxref("Object.is()")}}
-
Membandingkan dua nilai yang berbeda (mis. the same)
-
{{jsxref("Object.isExtensible()")}}
-
Menentukan apakah memperluas objek di perbolehkan.
-
{{jsxref("Object.isFrozen()")}}
-
Menentukan apakah objek telah beku.
-
{{jsxref("Object.isSealed()")}}
-
Menentukan apakah objek adalah sealed.
-
{{jsxref("Object.keys()")}}
-
Menegembalikan array berisi nama dari semua objek properti own enumerable.
-
{{jsxref("Object.preventExtensions()")}}
-
Mencegah ekstensi dari sebuah objek.
-
{{jsxref("Object.seal()")}}
-
Mencegah kode lain dari penghapusan properti dari sebuah objek.
-
{{jsxref("Object.setPrototypeOf()")}}
-
Mengatur prototype (mis., internal properti [[Prototype]])
-
{{jsxref("Object.values()")}} {{experimental_inline}}
-
Mengembalikan array dari objek nilai own enumerable.
-
- -

Perumpamaan Object dan Object prototype objek

- -

Pada JavaScript, semua objek diturunkan dari Object; dan semua objek mewarisi method dan property dari {{jsxref("Object.prototype")}}, meskipun hal tersebut telah di-override (diganti). Sebagai contoh, prototipe konstruktor lain mengesampingkan properti konstruktor dan menyediakan metode toString() yang spesifik. Perubahan ke objek prototipe Object disebarkan ke semua objek kecuali properti dan metode yang telah diubah sebelumnya diganti di sepanjang rantai prototipe.

- -

Properti

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
- -

Method

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
- -

Contoh

- -

Using Object given undefined and null types

- -

Dibawah ini adalah contoh menyimpan objek kosong pada variabel o:

- -
var o = new Object();
-
- -
var o = new Object(undefined);
-
- -
var o = new Object(null);
-
- -

Using Object to create Boolean objects

- -

Dibawah ini adalah contoh menyimpan objek {{jsxref("Boolean")}} pada variabel o:

- -
// equivalent to o = new Boolean(true);
-var o = new Object(true);
-
- -
// equivalent to o = new Boolean(false);
-var o = new Object(Boolean());
-
- -

Rincian Teknis

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diterapkan di JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}}-
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} -

Penambahan Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is

-
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Penambahan Object.entries, Object.values, dan Object.getOwnPropertyDescriptors.
- -

Kesesuaian browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/object/keys/index.html b/files/id/web/javascript/reference/global_objects/object/keys/index.html deleted file mode 100644 index cc1c7dc1a9..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/keys/index.html +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: Object.keys() -slug: Web/JavaScript/Reference/Global_Objects/Object/keys -translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys ---- -
{{JSRef}}
- -

Object.keys() Metode mengembalikan array dari objek yang diberikan sendiri enumerable properti, dalam urutan yang sama seperti yang disediakan oleh loop {{jsxref("Statements/for...in", "for...in")}} (perbedaan adalah bahwa sebuah loop for-in enumerates properti dalam mata rantai prototipe juga).

- -

Syntax

- -
Object.keys(obj)
- -

Parameters

- -
-
obj
-
Objek yang propertinya sendiri enumerable yang harus dikembalikan.
-
- -

Description

- -

Object.keys() mengembalikan array yang elemen string yang sesuai dengan properti enumerable yang ditemukan langsung pada objek. Urutan properti adalah sama dengan yang diberikan oleh perulangan / looping melalui properti dari objek secara manual.

- -

Examples

- -
var arr = ['a', 'b', 'c'];
-console.log(Object.keys(arr)); // console: ['0', '1', '2']
-
-// array like object
-var obj = { 0: 'a', 1: 'b', 2: 'c' };
-console.log(Object.keys(obj)); // console: ['0', '1', '2']
-
-// array like object with random key ordering
-var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
-console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
-
-// getFoo is property which isn't enumerable
-var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
-my_obj.foo = 1;
-
-console.log(Object.keys(my_obj)); // console: ['foo']
-
- -

Jika Anda ingin semua properti, bahkan tidak enumerables, lihat {{jsxref("Object.getOwnPropertyNames()")}}.

- -

Notes

- -

Dalam ES5, jika argumen untuk metode ini bukan merupakan objek (primitive), maka akan menyebabkan {{jsxref("TypeError")}}. Dalam ES6, argumen tidak-objek akan dipaksa untuk sebuah objek.

- -
Object.keys("foo");
-// TypeError: "foo" is not an object (ES5 code)
-
-Object.keys("foo");
-// ["0", "1", "2"]                   (ES6 code)
-
- -

Polyfill

- -

Untuk menambahkan kompatibel Object.keys dukungan dalam lingkungan yang lebih tua yang tidak native mendukung itu, copy potongan berikut:

- -
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
-if (!Object.keys) {
-  Object.keys = (function() {
-    'use strict';
-    var hasOwnProperty = Object.prototype.hasOwnProperty,
-        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
-        dontEnums = [
-          'toString',
-          'toLocaleString',
-          'valueOf',
-          'hasOwnProperty',
-          'isPrototypeOf',
-          'propertyIsEnumerable',
-          'constructor'
-        ],
-        dontEnumsLength = dontEnums.length;
-
-    return function(obj) {
-      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
-        throw new TypeError('Object.keys called on non-object');
-      }
-
-      var result = [], prop, i;
-
-      for (prop in obj) {
-        if (hasOwnProperty.call(obj, prop)) {
-          result.push(prop);
-        }
-      }
-
-      if (hasDontEnumBug) {
-        for (i = 0; i < dontEnumsLength; i++) {
-          if (hasOwnProperty.call(obj, dontEnums[i])) {
-            result.push(dontEnums[i]);
-          }
-        }
-      }
-      return result;
-    };
-  }());
-}
-
- -

Harap dicatat bahwa kode di atas termasuk kunci non-enumerable di  IE7 (dan mungkin IE8), ketika lewat di sebuah objek dari berbagai window.

- -

Untuk Browser sederhana Polyfill, lihat Javascript - Object.keys Browser Compatibility.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html deleted file mode 100644 index 3899fef48f..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Object.preventExtensions() -slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions -translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions ---- -
{{JSRef}}
- -

Metode Object.preventExtensions() mencegah properti-properti baru untuk ditambahkan pada sebuah obyek (mencegah ekstensi di masa depan pada sebuah obyek).

- -

Sintaks

- -
Object.preventExtensions(obj)
- -

Parameter

- -
-
obj
-
Obyek yang akan dibuat menjadi non-ekstensibel.
-
- -

Pengembalian nilai

- -

Obyek yang telah dibuat non-ekstensibel.

- -

Deskripsi

- -

 

- -

Sebuah obyek disebut ekstensibel jika properti baru dapat ditambahkan ke dalamnya . Object.preventExtensions() menandai suatu obyek untuk menjadi tidak ekstensibel, sehingga tidak akan pernah memiliki properti diluar properti-properti yang dimiliki sebelum ditandai sebagai non-ekstensibel. Perhatikan bahwa properti-properti obyek non-ekstensibel, secara umum, masih dapat dihapus. Mencoba untuk menambah properti baru ke obyek non-ekstensibel akan gagal, baik secara diam-diam atau dengan melemparkan {{jsxref("TypeError")}} (paling umum, tetapi tidak secara eksklusif,  ketika berada di {{jsxref("Functions_and_function_scope/Strict_mode", "strict mode", "", 1)}}).

- -

Object.preventExtensions() hanya mencegah penambahan properti sendiri . Sifat masih bisa ditambahkan ke prototipe obyek. Namun, memanggil Object.preventExtensions() pada obyek juga akan mencegah ekstensi / penambahan properti {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}}.

- -

Jika ada cara untuk mengubah suatu obyek ekstensibel untuk satu non-ekstensibel, tidak ada cara untuk melakukan yang sebaliknya di ECMAScript 5 .

- -

Contoh

- -
// Object.preventExtensions returns the object being made non-extensible.
-var obj = {};
-var obj2 = Object.preventExtensions(obj);
-obj === obj2; // true
-
-// Objects are extensible by default.
-var empty = {};
-Object.isExtensible(empty); // === true
-
-// ...but that can be changed.
-Object.preventExtensions(empty);
-Object.isExtensible(empty); // === false
-
-// Object.defineProperty throws when adding a new property to a non-extensible object.
-var nonExtensible = { removable: true };
-Object.preventExtensions(nonExtensible);
-Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError
-
-// In strict mode, attempting to add new properties to a non-extensible object throws a TypeError.
-function fail() {
-  'use strict';
-  nonExtensible.newProperty = 'FAIL'; // throws a TypeError
-}
-fail();
-
-// EXTENSION (only works in engines supporting __proto__
-// (which is deprecated. Use Object.getPrototypeOf instead)):
-// A non-extensible object's prototype is immutable.
-var fixed = Object.preventExtensions({});
-fixed.__proto__ = { oh: 'hai' }; // throws a TypeError
-
- -

Catatan

- -

Pada ES5, jika argumen pada fungsi metode ini adalah bukan sebuah obyek (sebuah tipe data primitif), maka hal itu akan menyebabkan {{jsxref("TypeError")}}. Pada ES6, sebuah argumen non-obyek akan diperlakukan seperti obyek tersebut obyek biasa yang non-ekstensibel, dan langsung mengembalikan nilai. 

- -
Object.preventExtensions(1);
-// TypeError: 1 is not an object (ES5 code)
-
-Object.preventExtensions(1);
-// 1                             (ES6 code)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}{{Spec2('ES5.1')}}Definisi awal. Terimplementasi pada JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ESDraft')}} 
- -

Browser kompatibilitas

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
ES6 behavior for non-object argument{{CompatChrome("44")}}{{CompatGeckoDesktop("35.0")}}{{CompatIE("11")}}{{CompatOpera("31")}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ES6 behavior for non-object argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/catch/index.html b/files/id/web/javascript/reference/global_objects/promise/catch/index.html deleted file mode 100644 index f2d5e38e8f..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/catch/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Promise.prototype.catch() -slug: Web/JavaScript/Reference/Global_Objects/Promise/catch -tags: - - ECMAScript6 - - Method - - Promise - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch ---- -
{{JSRef}}
- -

Method catch() mengembalikan Promise dan hanya setuju jika kasusnya gagal. Sama halnya dengan memenggil method {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}.

- -

Sintaks

- -
p.catch(onRejected);
-
-p.catch(function(reason) {
-   // rejection
-});
-
- -

Parameter

- -
-
onRejected
-
 {{jsxref("Function")}} dipanggil ketika Promise ditolak. Fungsi ini memiliki satu argumen, alasan penolakan.
-
- -

Deskripsi

- -

Method catch sangat berguna untuk menangani error di gabungan promis anda.

- -

Contoh

- -

Penggunaan method catch

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve('Success');
-});
-
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  throw 'oh, no!';
-}).catch(function(e) {
-  console.log(e); // "oh, no!"
-}).then(function(){
-  console.log('after a catch the chain is restored');
-}, function () {
-  console.log('Not fired due to the catch');
-});
-
-// The following behaves the same as above
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  return Promise.reject('oh, no!');
-}).catch(function(e) {
-  console.log(e); // "oh, no!"
-}).then(function(){
-  console.log('after a catch the chain is restored');
-}, function () {
-  console.log('Not fired due to the catch');
-});
-
-
- -

Promis tidak dapat mendeteksi error pada asynchronous callback

- -
var p1 = new Promise(function(resolve, reject) {
-  throw 'Uh-oh!';
-});
-
-p1.catch(function(e) {
-  console.log(e); // "Uh-oh!"
-});
-
-
-var p2 = new Promise(function(resolve, reject) {
-  setTimeout(function() {
-    throw 'Uncaught Exception!';
-  }, 1000);
-});
-
-p2.catch(function(e) {
-  console.log(e); // This is never called
-});
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

 

- - - -

{{Compat("javascript.builtins.Promise.catch")}}

- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/index.html b/files/id/web/javascript/reference/global_objects/promise/index.html deleted file mode 100644 index 240915ba23..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/index.html +++ /dev/null @@ -1,317 +0,0 @@ ---- -title: Promise -slug: Web/JavaScript/Reference/Global_Objects/Promise -tags: - - ECMAScript6 - - JavaScript - - NeedsTranslation - - Promise - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Promise ---- -
{{JSRef}}
- -

The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.

- -

Syntax

- -
new Promise( /* executor */ function(resolve, reject) { ... } );
- -

Parameters

- -
-
executor
-
A function that will be passed to other functions via the arguments resolve and reject. The executor function is executed immediately by the Promise implementation which provides the resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions are bound to the promise and calling them fulfills or rejects the promise, respectively. The executor is expected to initiate some asynchronous work and then, once that completes, call either the resolve or reject function to resolve the promise's final value or else reject it if an error occurred.
-
- -

Description

- -

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

- -

A Promise is in one of these states:

- - - -

A pending promise can become either fulfilled with a value, or rejected with a reason (error). When either of these happens, the associated handlers queued up by a promise's then method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)

- -

As the {{jsxref("Promise.then", "Promise.prototype.then()")}} and {{jsxref("Promise.catch", "Promise.prototype.catch()")}} methods return promises, they can be chained—an operation called composition.

- -

- -
-

Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's States and fates contains more details about promise terminology.

-
- -

Properties

- -
-
Promise.length
-
Length property whose value is 1 (number of constructor arguments).
-
{{jsxref("Promise.prototype")}}
-
Represents the prototype for the Promise constructor.
-
- -

Methods

- -
-
{{jsxref("Promise.all", "Promise.all(iterable)")}}
-
Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises together.
-
{{jsxref("Promise.race", "Promise.race(iterable)")}}
-
Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
-
- -
-
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
-
Returns a Promise object that is rejected with the given reason.
-
- -
-
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
-
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you want to know if a value is a promise or not - {{jsxref("Promise.resolve", "Promise.resolve(value)")}} it instead and work with the return value as a promise.
-
- -

Promise prototype

- -

Properties

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

- -

Methods

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

- -

Examples

- -

Creating a Promise

- - - -

This small example shows the mechanism of a Promise. The testPromise() method is called each time the {{HTMLElement("button")}} is clicked. It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the promise count (number starting from 1) every 1-3 seconds, at random. The Promise() constructor is used to create the promise.

- -

The fulfillment of the promise is simply logged, via a fulfill callback set using {{jsxref("Promise.prototype.then()","p1.then()")}}. A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.

- -
'use strict';
-var promiseCount = 0;
-
-function testPromise() {
-    var thisPromiseCount = ++promiseCount;
-
-    var log = document.getElementById('log');
-    log.insertAdjacentHTML('beforeend', thisPromiseCount +
-        ') Started (<small>Sync code started</small>)<br/>');
-
-    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
-    var p1 = new Promise(
-        // The resolver function is called with the ability to resolve or
-        // reject the promise
-        function(resolve, reject) {
-            log.insertAdjacentHTML('beforeend', thisPromiseCount +
-                ') Promise started (<small>Async code started</small>)<br/>');
-            // This is only an example to create asynchronism
-            window.setTimeout(
-                function() {
-                    // We fulfill the promise !
-                    resolve(thisPromiseCount);
-                }, Math.random() * 2000 + 1000);
-        }
-    );
-
-    // We define what to do when the promise is resolved/fulfilled with the then() call,
-    // and the catch() method defines what to do if the promise is rejected.
-    p1.then(
-        // Log the fulfillment value
-        function(val) {
-            log.insertAdjacentHTML('beforeend', val +
-                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
-        })
-    .catch(
-        // Log the rejection reason
-        function(reason) {
-            console.log('Handle rejected promise ('+reason+') here.');
-        });
-
-    log.insertAdjacentHTML('beforeend', thisPromiseCount +
-        ') Promise made (<small>Sync code terminated</small>)<br/>');
-}
- - - -

This example is executed when clicking the button. You need a browser supporting Promise. By clicking several times the button in a short amount of time, you'll even see the different promises being fulfilled one after the other.

- -

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

- -

Example using new XMLHttpRequest()

- -

Creating a Promise

- -

This example shows the implementation of a method which uses a Promise to report the success or failure of an {{domxref("XMLHttpRequest")}}.

- -
'use strict';
-
-// A-> $http function is implemented in order to follow the standard Adapter pattern
-function $http(url){
-
-  // A small example of object
-  var core = {
-
-    // Method that performs the ajax request
-    ajax : function (method, url, args) {
-
-      // Creating a promise
-      var promise = new Promise( function (resolve, reject) {
-
-        // Instantiates the XMLHttpRequest
-        var client = new XMLHttpRequest();
-        var uri = url;
-
-        if (args && (method === 'POST' || method === 'PUT')) {
-          uri += '?';
-          var argcount = 0;
-          for (var key in args) {
-            if (args.hasOwnProperty(key)) {
-              if (argcount++) {
-                uri += '&';
-              }
-              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
-            }
-          }
-        }
-
-        client.open(method, uri);
-        client.send();
-
-        client.onload = function () {
-          if (this.status >= 200 && this.status < 300) {
-            // Performs the function "resolve" when this.status is equal to 2xx
-            resolve(this.response);
-          } else {
-            // Performs the function "reject" when this.status is different than 2xx
-            reject(this.statusText);
-          }
-        };
-        client.onerror = function () {
-          reject(this.statusText);
-        };
-      });
-
-      // Return the promise
-      return promise;
-    }
-  };
-
-  // Adapter pattern
-  return {
-    'get' : function(args) {
-      return core.ajax('GET', url, args);
-    },
-    'post' : function(args) {
-      return core.ajax('POST', url, args);
-    },
-    'put' : function(args) {
-      return core.ajax('PUT', url, args);
-    },
-    'delete' : function(args) {
-      return core.ajax('DELETE', url, args);
-    }
-  };
-};
-// End A
-
-// B-> Here you define its functions and its payload
-var mdnAPI = 'https://developer.mozilla.org/en-US/search.json';
-var payload = {
-  'topic' : 'js',
-  'q'     : 'Promise'
-};
-
-var callback = {
-  success : function(data){
-     console.log(1, 'success', JSON.parse(data));
-  },
-  error : function(data){
-     console.log(2, 'error', JSON.parse(data));
-  }
-};
-// End B
-
-// Executes the method call
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success)
-  .catch(callback.error);
-
-// Executes the method call but an alternative way (1) to handle Promise Reject case
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success, callback.error);
-
-// Executes the method call but an alternative way (2) to handle Promise Reject case
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success)
-  .then(undefined, callback.error);
-
- -

Loading an image with XHR

- -

Another simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

 

- -
- - -

{{Compat("javascript.builtins.Promise")}}

-
- -

 

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/reject/index.html b/files/id/web/javascript/reference/global_objects/promise/reject/index.html deleted file mode 100644 index 180fcc5571..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/reject/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Promise.reject() -slug: Web/JavaScript/Reference/Global_Objects/Promise/reject -tags: - - ECMAScript6 - - Method - - Promise - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject ---- -
{{JSRef}}
- -

Method Promise.reject(reason) mengembalikan objek Promise yang ditolak dengan alasan yang diberikan.

- -

Sintaks

- -
Promise.reject(reason);
- -

Parameter

- -
-
reason
-
Alasan kenapa Promise ditolak.
-
- -

Deskripsi

- -

Fungsi static Promise.reject mengembalikan Promise yang ditolak. Untuk keperluan debugging dan seleksi penankapan error, sangat berguna untuk membuat reason pada instanceof {{jsxref("Error")}}.

- -

Contoh

- -

Penggunaan mthod static Promise.reject()

- -
Promise.reject("Testing static reject").then(function(reason) {
-  // not called
-}, function(reason) {
-  console.log(reason); // "Testing static reject"
-});
-
-Promise.reject(new Error("fail")).then(function(error) {
-  // not called
-}, function(error) {
-  console.log(error); // Stacktrace
-});
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- - - -

{{Compat("javascript.builtins.Promise.reject")}}

- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/resolve/index.html b/files/id/web/javascript/reference/global_objects/promise/resolve/index.html deleted file mode 100644 index d958ab4d52..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/resolve/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: Promise.resolve() -slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve -tags: - - ECMAScript6 - - JavaScript - - Method - - Promise -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve ---- -
{{JSRef}}
- -

Method Promise.resolve(value) mengembalikan objek {{jsxref("Promise.then")}} yang diselesaikan dengan nilai yang diberikan. jika nilainya thenable (mis. memiliki {{jsxref("Promise.then", "\"then\" method")}}), promise yang dikembalikan akan "mengikuti" thenable-nya, menggunakan keadaan ini; sebaliknya promise akan dikembalikan sesuai nilai yang terpenuhi.

- -

Sintaks

- -
Promise.resolve(value);
-Promise.resolve(promise);
-Promise.resolve(thenable);
-
- -

Parameter

- -
-
value
-
Argumen untuk diselesaikan oleh Promise. Dapat juga sebuah Promise atau thenable untuk diselesaikan.
-
- -

Deskripsi

- -

Fungsi statis Promise.resolve mengembalikan Promise yang terselesaikan.

- -

Contoh

- -

Penggunaan method static Promise.resolve

- -
Promise.resolve("Success").then(function(value) {
-  console.log(value); // "Success"
-}, function(value) {
-  // not called
-});
-
- -

Penyelesaian pada array

- -
var p = Promise.resolve([1,2,3]);
-p.then(function(v) {
-  console.log(v[0]); // 1
-});
-
- -

Penyelesaian pada Promise lain

- -
var original = Promise.resolve(true);
-var cast = Promise.resolve(original);
-cast.then(function(v) {
-  console.log(v); // true
-});
-
- -

Penyelesaian thenables dan throwing Errors

- -
// Resolving a thenable object
-var p1 = Promise.resolve({
-  then: function(onFulfill, onReject) { onFulfill("fulfilled!"); }
-});
-console.log(p1 instanceof Promise) // true, object casted to a Promise
-
-p1.then(function(v) {
-    console.log(v); // "fulfilled!"
-  }, function(e) {
-    // not called
-});
-
-// Thenable throws before callback
-// Promise rejects
-var thenable = { then: function(resolve) {
-  throw new TypeError("Throwing");
-  resolve("Resolving");
-}};
-
-var p2 = Promise.resolve(thenable);
-p2.then(function(v) {
-  // not called
-}, function(e) {
-  console.log(e); // TypeError: Throwing
-});
-
-// Thenable throws after callback
-// Promise resolves
-var thenable = { then: function(resolve) {
-  resolve("Resolving");
-  throw new TypeError("Throwing");
-}};
-
-var p3 = Promise.resolve(thenable);
-p3.then(function(v) {
-  console.log(v); // "Resolving"
-}, function(e) {
-  // not called
-});
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

 

- - - -

{{Compat("javascript.builtins.Promise.resolve")}}

- -

 

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/then/index.html b/files/id/web/javascript/reference/global_objects/promise/then/index.html deleted file mode 100644 index 5a1e275c8c..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/then/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Promise.prototype.then() -slug: Web/JavaScript/Reference/Global_Objects/Promise/then -tags: - - ECMAScript6 - - JavaScript - - Method - - Promise - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then ---- -
{{JSRef}}
- -

Method then() mengembalikan {{domxref("Promise")}}. Menggunakan dua argumen: fungsi callback untuk kasus sukses dan gagal pada Promise.

- -

Sintaks

- -
p.then(onFulfilled, onRejected);
-
-p.then(function(value) {
-   // fulfillment
-  }, function(reason) {
-  // rejection
-});
-
- -

Parameter

- -
-
onFulfilled
-
{{jsxref("Function")}} dipanggil ketika Promise dipenuhi. Fungsi ini memiliki satu argumen, value pemenuhan.
-
onRejected
-
{{jsxref("Function")}} dipangil ketika Promise ditolak. fungsi ini memiliki satau argumen, alasan penolakan.
-
- -

Deskripsi

- -

Kedua method then dan {{jsxref("Promise.prototype.catch()")}} megembalikan promis, juga dapat dirantaikan — operasi yang disebut composition.

- -

Contoh

- -

Meggunakan method then

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve("Success!");
-  // or
-  // reject ("Error!");
-});
-
-p1.then(function(value) {
-  console.log(value); // Success!
-}, function(reason) {
-  console.log(reason); // Error!
-});
-
- -

Perantaian

- -

Karena method then mengembalikan Promise, anda bisa merantaikan pemanggilan then.

- -
var p2 = new Promise(function(resolve, reject) {
-  resolve(1);
-});
-
-p2.then(function(value) {
-  console.log(value); // 1
-  return value + 1;
-}).then(function(value) {
-  console.log(value); // 2
-});
-
-p2.then(function(value) {
-  console.log(value); // 1
-});
-
- -

Anda juga bisa menggunakan perantaian untuk melaksanakan satu fungsi dengan sebuah Promise berbasis API diatas fungsi lainnya.

- -
function fetch_current_data() {
-  // The fetch() API returns a Promise.  This function
-  // exposes a similar API, except the fulfillment
-  // value of this function's Promise has had more
-  // work done on it.
-  return fetch("current-data.json").then((response) => {
-    if (response.headers.get("content-type") != "application/json") {
-      throw new TypeError();
-    }
-    var j = response.json();
-    // maybe do something with j
-    return j; // fulfillment value given to user of
-              // fetch_current_data().then()
-  });
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- - - -

{{Compat("javascript.builtins.Promise.then")}}

- -

 

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/regexp/index.html b/files/id/web/javascript/reference/global_objects/regexp/index.html deleted file mode 100644 index 8bd6dce4b9..0000000000 --- a/files/id/web/javascript/reference/global_objects/regexp/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: RegExp -slug: Web/JavaScript/Reference/Global_Objects/RegExp -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp ---- -
{{JSRef}}

The RegExpobjek digunakan untuk pencocokan teks dengan pola.

- -

Untuk pengantar ekspresi reguler, baca bab Ekspresi Reguler di Panduan JavaScript .

- -

Deskripsi

- -

Notasi dan konstruktor literal

- -

Ada dua cara untuk membuat RegExpobjek: notasi literal dan konstruktor .

- - - -

Tiga ekspresi berikut membuat ekspresi reguler yang sama:

- -
/ab+c/i
-new RegExp(/ab+c/, 'i') // literal notation
-new RegExp('ab+c', 'i') // constructor
-
- -

Notasi literal menghasilkan kompilasi dari ekspresi reguler ketika ekspresi dievaluasi. Gunakan notasi literal ketika ekspresi reguler akan tetap konstan. Misalnya, jika Anda menggunakan notasi literal untuk membuat ekspresi reguler yang digunakan dalam satu lingkaran, ekspresi reguler tidak akan dikompilasi ulang pada setiap iterasi.

- -

Konstruktor objek ekspresi reguler — misalnya, new RegExp('ab+c')—menghasilkan kompilasi runtime dari ekspresi reguler. Gunakan fungsi konstruktor ketika Anda tahu pola ekspresi reguler akan berubah, atau Anda tidak tahu pola dan mendapatkannya dari sumber lain, seperti input pengguna.

- -

Bendera dalam konstruktor

- -

Dimulai dengan ECMAScript 6, new RegExp(/ab+c/, 'i')tidak lagi melempar a TypeError"can't supply flags when constructing one RegExp from another") ketika argumen pertama adalah a RegExpdan flagsargumen kedua hadir. Sebagai RegExpgantinya, argumen baru dibuat.

- -

Saat menggunakan fungsi konstruktor, aturan pelolosan string normal (mendahului karakter khusus \ketika disertakan dalam string) diperlukan.

- -

Misalnya, yang berikut ini setara:

- -
let re = /\w+/
-let re = new RegExp('\\w+')
-
- -

Properti Reg-suka seperti Perl

- -

Perhatikan bahwa beberapa RegExpproperti memiliki nama panjang dan pendek (seperti Perl). Kedua nama selalu merujuk pada nilai yang sama. (Perl adalah bahasa pemrograman tempat JavaScript memodelkan ekspresi regulernya.). Lihat juga properti yang sudah usang RegExp.

- -

Konstruktor

- -
-
RegExp()
-
Menciptakan RegExpobjek baru .
-
- -

Sifat statis

- -
-
get RegExp[@@species]
-
The constructor function that is used to create derived objects.
-
RegExp.lastIndex
-
The index at which to start the next match.
-
- -

Instance properties

- -
-
RegExp.prototype.flags
-
A string that contains the flags of the RegExp object.
-
RegExp.prototype.dotAll
-
Whether . matches newlines or not.
-
RegExp.prototype.global
-
Whether to test the regular expression against all possible matches in a string, or only against the first.
-
RegExp.prototype.ignoreCase
-
Whether to ignore case while attempting a match in a string.
-
RegExp.prototype.multiline
-
Whether or not to search in strings across multiple lines.
-
RegExp.prototype.source
-
The text of the pattern.
-
RegExp.prototype.sticky
-
Whether or not the search is sticky.
-
RegExp.prototype.unicode
-
Whether or not Unicode features are enabled.
-
- -

Instance methods

- -
-
RegExp.prototype.compile()
-
(Re-)compiles a regular expression during execution of a script.
-
RegExp.prototype.exec()
-
Executes a search for a match in its string parameter.
-
RegExp.prototype.test()
-
Tests for a match in its string parameter.
-
RegExp.prototype.toString()
-
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.
-
RegExp.prototype[@@match]()
-
Performs match to given string and returns match result.
-
RegExp.prototype[@@matchAll]()
-
Returns all matches of the regular expression against a string.
-
RegExp.prototype[@@replace]()
-
Replaces matches in given string with new substring.
-
RegExp.prototype[@@search]()
-
Searches the match in given string and returns the index the pattern found in the string.
-
RegExp.prototype[@@split]()
-
Splits given string into an array by separating the string into substring.
-
- -

Examples

- -

Using a regular expression to change data format

- -

The following script uses the replace() method of the String instance to match a name in the format first last and output it in the format last, first.

- -

In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

- -
let re = /(\w+)\s(\w+)/
-let str = 'John Smith'
-let newstr = str.replace(re, '$2, $1')
-console.log(newstr)
-
- -

This displays "Smith, John".

- -

Using regular expression to split lines with different line endings/ends of line/line breaks

- -

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

- -
let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
-let lines = text.split(/\r\n|\r|\n/)
-console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
-
- -

Note that the order of the patterns in the regular expression matters.

- -

Using regular expression on multiple lines

- -
let s = 'Please yes\nmake my day!'
-
-s.match(/yes.*day/);
-// Returns null
-
-s.match(/yes[^]*day/);
-// Returns ["yes\nmake my day"]
-
- -

Using a regular expression with the sticky flag

- -

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex.

- -
let str = '#foo#'
-let regex = /foo/y
-
-regex.lastIndex = 1
-regex.test(str)      // true
-regex.lastIndex = 5
-regex.test(str)      // false (lastIndex is taken into account with sticky flag)
-regex.lastIndex      // 0 (reset after match failure)
- -

The difference between the sticky flag and the global flag

- -

With the sticky flag y, the next match has to happen at the lastIndex position, while with the global flag g, the match can happen at the lastIndex position or later:

- -
re = /\d/y;
-while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);
-
-// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
-// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
-// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
-//   ... and no more match.
- -

With the global flag g, all 6 digits would be matched, not just 3.

- -

Regular expression and Unicode characters

- -

As mentioned above, \w or \W only matches ASCII based characters; for example, a to zA to Z0 to 9, and _.

- -

To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh, where hhhh is the character's Unicode value in hexadecimal.

- -

This example demonstrates how one can separate out Unicode characters from a word.

- -
let text = 'Образец text на русском языке'
-let regex = /[\u0400-\u04FF]+/g
-
-let match = regex.exec(text)
-console.log(match[0])        // logs 'Образец'
-console.log(regex.lastIndex) // logs '7'
-
-let match2 = regex.exec(text)
-console.log(match2[0])       // logs 'на' [did not log 'text']
-console.log(regex.lastIndex) // logs '15'
-
-// and so on
-
- -

The Unicode property escapes feature introduces a solution, by allowing for a statement as simple as \p{scx=Cyrl}. One can also use an external resource for getting the complete Unicode block range for different scripts, such as Regexp-Unicode-block.

- -

Extracting sub-domain name from URL

- -
let url = 'http://xxx.domain.com'
-console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
-
- -

Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the URL API.

- -

Specifications

- - - - - - - - - - - - -
Specification
ECMAScript (ECMA-262)
- The definition of 'RegExp' in that specification.
- -

Browser compatibility

- -

{{Compat("javascript.builtins.RegExp")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/charat/index.html b/files/id/web/javascript/reference/global_objects/string/charat/index.html deleted file mode 100644 index e464f2bd4c..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/charat/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: String.prototype.charAt() -slug: Web/JavaScript/Reference/Global_Objects/String/charAt -translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt ---- -
{{JSRef}}
- -

Method charAt() pada Objek {{jsxref("String")}} mengembalikan string baru yang berisi kode lokasi single UTF-16 pada offset yang ditentukan ke dalam string.

- -
{{EmbedInteractiveExample("pages/js/string-charat.html", "shorter")}}
- - - -

Syntax

- -
let character = str.charAt(index)
- -

Parameter

- -
-
index
-
Sebuah integer antara 0 sampai str.length - 1. Bila nilai index bukan dalam bentuk integer atau index tidak ditentukan, maka nilai index akan bernilai 0, sehingga karakter pertama varibel str akan dikembalikan/ di-return.
-
- -

Nilai Return

- -

Sebuah string yang merepresentasikan sebuah karakter pada indeks tertentu. Jika index indeks berada di luar range, maka charAt()  akan me-return string kosong.

- -

Deskripsi

- -

Karakter dalam sebuah string diberi indeks dari kiri ke kanan. Indeks karakter pertama adalah 0, dan index karakter terakhir dalam string — misal nama stringnya stringName, adalah stringName.length - 1. Jika indeks yang anda berikan diluar range ini, maka JavaScript akan me-return string kosong.

- -

Jika tidak ada indeks yang tertera pada charAt(), maka nilai defaultnya adalah 0.

- -

Contoh

- -

Menampilkan karakter pada lokasi yang berbeda pada sebuah string

- -

Contoh berikut menunjukan karakter di lokasi berbeda pada string "Brave new world":

- -
var anyString = 'Brave new world';
-console.log("The character at index 0   is '" + anyString.charAt()   + "'");
-// Tidak ada angka yang tertera pada charAt(), maka digunakan nilai 0 sebagai default
-
-console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
-console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
-console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
-console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
-console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
-console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
-
- -

Baris kode di atas menghasilkan output sebagai berikut:

- -
The character at index 0   is 'B'
-
-The character at index 0   is 'B'
-The character at index 1   is 'r'
-The character at index 2   is 'a'
-The character at index 3   is 'v'
-The character at index 4   is 'e'
-The character at index 999 is ''
-
- -

Mendapatkan seluruh karakter

- -

Berikut ini adalah cara untuk memastikan bahwa melalui loop string selalu memberikan karakter utuh, meskipun string berisi karakter yang tidak ada dalam Bidang Multilingual Dasar.

- -
var str = 'A \uD87E\uDC04 Z'; // Kita bisa menggunakan karakter non-BMP
-for (var i = 0, chr; i < str.length; i++) {
-  if ((chr = getWholeChar(str, i)) === false) {
-    continue;
-  }
-  // Adapt this line at the top of each loop, passing in the whole string and
-  // the current iteration and returning a variable to represent the
-  // individual character
-
-  console.log(chr);
-}
-
-function getWholeChar(str, i) {
-  var code = str.charCodeAt(i);
-
-  if (Number.isNaN(code)) {
-    return ''; // Posisi tidak ditemukan
-  }
-  if (code < 0xD800 || code > 0xDFFF) {
-    return str.charAt(i);
-  }
-
-  // High surrogate (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 <= code && code <= 0xDBFF) {
-    if (str.length <= (i + 1)) {
-      throw 'High surrogate without following low surrogate';
-    }
-    var next = str.charCodeAt(i + 1);
-      if (0xDC00 > next || next > 0xDFFF) {
-        throw 'High surrogate without following low surrogate';
-      }
-      return str.charAt(i) + str.charAt(i + 1);
-  }
-  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
-  if (i === 0) {
-    throw 'Low surrogate without preceding high surrogate';
-  }
-  var prev = str.charCodeAt(i - 1);
-
-  // (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 > prev || prev > 0xDBFF) {
-    throw 'Low surrogate without preceding high surrogate';
-  }
-  // We can pass over low surrogates now as the second component
-  // in a pair which we have already processed
-  return false;
-}
-
- -

Pada environment ECMAScript 2016 yang memungkinkan assignment yang rusak, Berikut ini merupakan alternatif yang lebih ringkas dan fleksibel karena perulangan dilakukan penmabahan secara otomatis pada variabel increment/ penambahannya (jika karakter menjaminnya sebagai pasangan pengganti).

- -
let str = 'A\uD87E\uDC04Z'  // Kita juga dapat menggunakan karakter non-BMP
-for (let i = 0, chr; i < str.length; i++) {
-  [chr, i] = getWholeCharAndI(str, i)
-
-  // Adapt this line at the top of each loop, passing in the whole string and
-  // the current iteration and returning an array with the individual character
-  // and 'i' value (only changed if a surrogate pair)
-
-  console.log(chr)
-}
-
-function getWholeCharAndI(str, i) {
-  let code = str.charCodeAt(i)
-
-  if (Number.isNaN(code)) {
-    return ''  // Posisi tidak ditemukan
-  }
-  if (code < 0xD800 || code > 0xDFFF) {
-    return [str.charAt(i), i]  // Karakter normal, keeping 'i' the same
-  }
-
-  // High surrogate (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 <= code && code <= 0xDBFF) {
-    if (str.length <= (i + 1)) {
-      throw 'High surrogate without following low surrogate'
-    }
-    let next = str.charCodeAt(i + 1)
-      if (0xDC00 > next || next > 0xDFFF) {
-        throw 'High surrogate without following low surrogate'
-      }
-      return [str.charAt(i) + str.charAt(i + 1), i + 1]
-  }
-
-  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
-  if (i === 0) {
-    throw 'Low surrogate without preceding high surrogate'
-  }
-
-  let prev = str.charCodeAt(i - 1)
-
-  // (could change last hex to 0xDB7F to treat high private surrogates
-  // as single characters)
-  if (0xD800 > prev || prev > 0xDBFF) {
-    throw 'Low surrogate without preceding high surrogate'
-  }
-
-  // Return the next character instead (and increment)
-  return [str.charAt(i + 1), i + 1]
-}
-
- -

Memperbaiki charAt() untuk mendukung karakter non-Basic-Multilingual-Plane (BMP)

- -

Pada contoh sebelumnya mungkin lebih berguna untuk program yang mendukung karakter non-BMP (karena tidak mengharuskan pemanggil untuk mengetahui dimana karakter non-BMP mungkin muncul), jika memang diinginkan, dalam memilih karakter dengan index, untuk memperlakukan pasangan pengganti dalam string sebagai karakter tunggal yang mereka wakili, dapat menggunakan yang berikut ini:

- -
function fixedCharAt(str, idx) {
-  let ret = ''
-  str += ''
-  let end = str.length
-
-  let surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
-  while ((surrogatePairs.exec(str)) != null) {
-    let lastIdx = surrogatePairs.lastIndex
-    if (lastIdx - 2 < idx) {
-      idx++
-    } else {
-      break
-    }
-  }
-
-  if (idx >= end || idx < 0) {
-    return ''
-  }
-
-  ret += str.charAt(idx)
-
-  if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
-    // Go one further, since one of the "characters" is part of a surrogate pair
-    ret += str.charAt(idx + 1)
-  }
-  return ret
-}
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.charAt")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/concat/index.html b/files/id/web/javascript/reference/global_objects/string/concat/index.html deleted file mode 100644 index 0ba2b2a156..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/concat/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: String.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/String/concat -tags: - - JavaScript - - Referensi - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/concat ---- -
{{JSRef}}
- -

Method concat() menggabungkan dua teks atau lebih menjadi sebuah string baru.

- -

Syntax

- -
str.concat(string2, string3[, ..., stringN])
- -

Parameter

- -
-
string2...stringN
-
String untuk menggabungkan string.
-
- -

Deskripsi

- -

Fungsi concat() menggabungkan teks dari satu atau lebih string dan mengembalikanya menjadi sebuah string. Perubahan pada salah satu teks tidak mempengaruhi string lainnya.

- -

Contoh

- -

Penggunaan concat()

- -

Untuk menggabungkan string menjadi sebuah string baru seperti pada contoh dibawah.

- -
var halo = 'Halo, ';
-console.log(halo.concat('Didik', ' semoga hari ini menyenangkan.'));
-
-/* Halo, Didik semoga hari ini menyenangkan. */
-
- -

Performa

- -

Sangat disarankan untuk menggunakan {{jsxref("Operators/Assignment_Operators", "assignment operators", "", 1)}} (+, +=) pada method concat(). lihat test performa berikut ini.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.6', 'String.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome untuk AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html deleted file mode 100644 index 786e32883e..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: String.fromCharCode() -slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode -tags: - - JavaScript - - Method - - Metode - - Reference - - Referensi - - String - - Unicode -translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode ---- -
{{JSRef}}
- -

Metode statis String.fromCharCode() mengembalikan sebuah string yang dibuat dari barisan nilai Unicode tertentu.

- -

Sintak

- -
String.fromCharCode(num1[, ...[, numN]])
- -

Parameter

- -
-
num1, ..., numN
-
Barisan dari angka-angka yang merupakan nilai Unicode.Jangkauannya antara 0 sampai dengan 65535(0xFFFF).Nomor yang lebih besar dari 0xFFFF dipotong.Tidak ada cek validasi yang dilakukan.   
-
- -

Nilai kembalian

- -

Sebuah string yang di dalamnya terdapat karakter-karakter sesuai nilai Unicode dari barisan angka yang diberikan.

- -

Deskripsi

- -

Metode ini mengembalikan sebuah string dan bukan objek {{jsxref("String")}}.

- -

Karena fromCharCode() merupakan metode statis dari {{jsxref("String")}}, Anda selalu bisa menggunakannya sebagai String.fromCharCode(), daripada sebagai metode dari objek {{jsxref("String")}} yang Anda buat.

- -

Contoh

- -

Menggunakan fromCharCode()

- -

Contoh di bawah ini mengembalikan string "ABC".

- -
String.fromCharCode(65, 66, 67);  // "ABC"
-
- -

Membuatnya bekerja dengan nilai yang lebih tinggi

- -

Meskipu nilai Unicode yang umum dapat digambarkan dengan satu angka 16-bit (seperti yang diharapkan pada awal mula standarisasi JavaScript) dan fromCharCode() dapat digunakan untuk mengembalikan sebuah karakter dari nilai yang paling umum (misal. nilai UCS-2 yang merupakan bagian dari UTF-16 dengan karakter yang paling umum digunakan). Untuk menghadapi SEMUA nilai Unicode yang sah (hingga 21 bit), fromCharCode() sendiri tidak dapat menghadapinya. Semenjak nilai code point karakter yang lebih tinggi menggunakan dua angka "pengganti"  (dengan nilai yang lebih rendah) untuk membuat sebuah karakter tunggal, {{jsxref("String.fromCodePoint()")}} (bagian dari draf ES6) dapat digunakan untuk menggunakan sepasang angka tersebut, sehingga dapat menampilkan karakter dengan nilai yang lebih tinggi.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan dalam JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.3.2', 'StringfromCharCode')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ESDraft')}}
- -

Kompabilitas peramban

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html b/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html deleted file mode 100644 index dc4024f941..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: String.fromCodePoint() -slug: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint -tags: - - ECMAScript 2015 - - JavaScript - - Metode - - Referensi - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint ---- -
{{JSRef}}
- -

Metode String.fromCodePoint() mengembalikan string yang dibuat dengan menggunakan urutan titik kode yang ditentukan.

- -
{{EmbedInteractiveExample("pages/js/string-fromcodepoint.html")}}
- - - -

Syntax

- -
String.fromCodePoint(num1[, ...[, numN]])
- -

Parameters

- -
-
num1, ..., numN
-
Urutan Poin Kode
-
- -

Return value

- -

String yang dibuat dengan menggunakan urutan titik kode yang ditentukan.

- -

Exceptions

- - - -

Description

- -

Metode ini mengembalikan string dan bukan sebuah objek. {{jsxref("String")}} .

- -

Karena fromCodePoint() adalah metode statik dari {{jsxref("String")}}, dan anda selalu menggunakannya sebagai String.fromCodePoint(), alih-alih sebagai sebuah metode yang anda buat {{jsxref("String")}}

- -

Examples

- -

Using fromCodePoint()

- -
String.fromCodePoint(42);       // "*"
-String.fromCodePoint(65, 90);   // "AZ"
-String.fromCodePoint(0x404);    // "\u0404"
-String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
-String.fromCodePoint(194564);   // "\uD87E\uDC04"
-String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
-
-String.fromCodePoint('_');      // RangeError
-String.fromCodePoint(Infinity); // RangeError
-String.fromCodePoint(-1);       // RangeError
-String.fromCodePoint(3.14);     // RangeError
-String.fromCodePoint(3e-2);     // RangeError
-String.fromCodePoint(NaN);      // RangeError
-
- -
// String.fromCharCode() sendiri tidak bisa mendapatkan karakter pada titik kode tinggi seperti itu
-// Disisi lain, dapat juga mengembalikan karakter 4-byte dan juga
-// yang biasa 2-byte (i.e., dapat mengembalikan satu karakter yang sebenarnya sudah dimiliki
-// string 2 daripada 1!)
-console.log(String.fromCodePoint(0x2F804)); // atau 194564 dalam bilangan desimal
-
- -

Polyfill

- -

Metode String.fromCodePoint telah ditambahkan ke ECMAScript 2015 dan mungkin belum didukung di semua browser web atau lingkungannya. Gunakan kode dibawah ini untuk polyfill:

- -
if (!String.fromCodePoint) (function(stringFromCharCode) {
-    var fromCodePoint = function(_) {
-      var codeUnits = [], codeLen = 0, result = "";
-      for (var index=0, len = arguments.length; index !== len; ++index) {
-        var codePoint = +arguments[index];
-        // correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
-        // The surrounding `!(...)` is required to correctly handle `NaN` cases
-        // The (codePoint>>>0) === codePoint clause handles decimals and negatives
-        if (!(codePoint < 0x10FFFF && (codePoint>>>0) === codePoint))
-          throw RangeError("Invalid code point: " + codePoint);
-        if (codePoint <= 0xFFFF) { // BMP code point
-          codeLen = codeUnits.push(codePoint);
-        } else { // Astral code point; split in surrogate halves
-          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
-          codePoint -= 0x10000;
-          codeLen = codeUnits.push(
-            (codePoint >> 10) + 0xD800,  // highSurrogate
-            (codePoint % 0x400) + 0xDC00 // lowSurrogate
-          );
-        }
-        if (codeLen >= 0x3fff) {
-          result += stringFromCharCode.apply(null, codeUnits);
-          codeUnits.length = 0;
-        }
-      }
-      return result + stringFromCharCode.apply(null, codeUnits);
-    };
-    try { // IE 8 only supports `Object.defineProperty` on DOM elements
-      Object.defineProperty(String, "fromCodePoint", {
-        "value": fromCodePoint, "configurable": true, "writable": true
-      });
-    } catch(e) {
-      String.fromCodePoint = fromCodePoint;
-    }
-}(String.fromCharCode));
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ES2015')}}Definisi Awal
{{SpecName('ESDraft', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.fromCodePoint")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/index.html b/files/id/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index 35f78502d5..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,371 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript6 - - JavaScript - - Reference - - Referensi - - Referensı(2) - - Référence(2) - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef("Global_Objects", "String")}}
- -

Ringkasan

- -

Objek global String adalah sebuah pembangun untuk string, atau sebuah rangkaian dari karakter.

- -

Sintak

- -

String secara harfiah berbentuk:

- -
'string text'
-"string text"
-"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"
-
- -

Sejak ECMAScript 6 String secara harfiah dapat juga menjadi Template Strings:

- -
`hello world`
-`hello!
- world!`
-`hello ${who}`
-escape `<a>${who}</a>`
- -

Selain karakter biasa yang dapat dicetak, karakter spesial dapat disandikan dengan notasi lepas:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
KodeKeluaran
\0karakter NUL
\'petik satu
\"petik dua
\\garis miring
\nbaris baru
\rcarriage return
\vtab vertikal
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXkarakter Latin-1
- -

Atau, menggunakan objek global String langsung:

- -
String(benda)
-new String(benda)
-
- -

Parameter

- -
-
benda
-
Apapun yang akan diubah ke string.
-
- -

Deskripsi

- -

String berguna untuk membawa data yang dapat diitampilkan dalam bentuk teks. Beberapa operasi yang paling sering digunakan dalam string adalah untuk memeriksa {{jsxref("String.length", "panjangnya")}}, untuk membuat dan menggabungkannya dengan operator string + dan +=, mengecek adanya atau lokasi dari substring dengan metode {{jsxref("String.prototype.indexOf()", "indexOf()")}}, atau mendapatkan substring dengan metode {{jsxref("String.prototype.substring()", "substring()")}}.

- -

Akses karakter

- -

Ada dua cara untuk mengakses sebuah karakter dalam string. Cara yang pertama adalah metode {{jsxref("String.prototype.charAt()", "charAt()")}}:

- -
return 'cat'.charAt(1); // mengembalikan "a"
-
- -

Cara yang lain (diperkenalkan dalam ECMAScript 5) adalah menganggap string sebagai objek mirip-susunan, di mana setiap karakter disesuaikan dengan indeks angka:

- -
return 'cat'[1]; // mengembalikan "a"
-
- -

Untuk akses karakter dengan menggunakan notasi kurung, mencoba untuk menghapus atau menetapkan nilai ke propertinya tidak akan berhasil. Properti yang terlibat tidak dapat ditulis maupun diubah. (Lihat {{jsxref("Object.defineProperty()")}} untuk informasi lebih.)

- -

Membandingkan string

- -

Pengembang C mempunyai fungsi strcmp() untuk membandingkan string. Dalam JavaScript, Anda cukup menggunakan operas kurang dari dan lebih dari:

- -
var a = 'a';
-var b = 'b';
-if (a < b) { // benar
-  print(a + ' kurang dari ' + b);
-} else if (a > b) {
-  print(a + ' lebih dari ' + b);
-} else {
-  print(a + ' sama dengan ' + b);
-}
-
- -

Hasil yang serupa dapat didapatkan dengan metode {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} yang diwariskan oleh benda String.

- -

Perbedaan antara string primitif dan objek String

- -

Ingat bahwa JavaScript membedakan nilai antara objek String dan string primitif. (Serupa dengan {{jsxref("Global_Objects/Boolean", "Boolean")}} dan {{jsxref("Global_Objects/Number", "Angka")}}.)

- -

String yang harfiah (ditandai dengan petik satu atau dua) dan string yang dikembalikan dari panggilan String dalam sebuah konteks non-pembangun (misal, tanpa menggunakan kata kunci {{jsxref("Operators/new", "new")}}) adalah string primitif. JavaScript secara otomatis mengubah primitif ke objek String, jadi mungkin untuk menggunakan metode objek String untuk string primitif. Dalam konteks di mana sebuah metode dipanggil pada string primitif atau sebuah pembacaan properti terjadi, JavaScript akan secara otomatis membungkus string primitif dan memanggil metode tersebut atau melakukan pembacaan properti.

- -
var s_prim = 'foo';
-var s_obj = new String(s_prim);
-
-console.log(typeof s_prim); // "string"
-console.log(typeof s_obj);  // "object"
-
- -

String primitif dan objek String juga memberikan hasil berbeda saat menggunakan {{jsxref("Global_Objects/eval", "eval()")}}. Primitif melewati eval sebagai kode sumber; Objek String dianggap semua objek lain, dengan mengembalikan objek tersebut. Sebagai contoh:

- -
var s1 = '2 + 2';             // membuat sebuah string primitif
-var s2 = new String('2 + 2'); // membuat sebuah objek String
-console.log(eval(s1));        // mengembalikan angka 4
-console.log(eval(s2));        // mengembalikan string "2 + 2"
-
- -

Untuk itu, kode mungkin berhenti saat menemui objek String saat mengharapkan string primitif, meskipun secara umum pembuat tidak perlu khawatir tentang perbedaannya.

- -

Sebuah objek String dapat selalu diubah menjadi kawan primitifnya dengan metode {{jsxref("String.prototype.valueOf()", "valueOf()")}}.

- -
console.log(eval(s2.valueOf())); // mengembalikan angka 4
-
- -
Catatan: Untuk kemungkinan lain ke string dalam JavaScript, mohon baca artikel tentang StringView — a C-like representation of strings based on typed arrays (bahasa Inggris).
- -

Properti

- -
-
{{jsxref("String.prototype")}}
-
Membolehkan penambahan properti ke sebuahobjek String.
-
- -
{{jsOverrides("Function", "Properties", "prototype")}}
- -

Metode

- -
-
{{jsxref("String.fromCharCode()")}}
-
Mengembalikan sebuah string yang dibuat dengan menggunakan nilai urutan Unicode.
-
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
-
Mengembalikan sebuah string dibuat dengan menggunakan urutan code points.
-
{{jsxref("String.raw()")}} {{experimental_inline}}
-
Mengembalikan sebuah string yang dibuat dari sebuah templat string mentah.
-
- -
{{jsOverrides("Function", "Methods", "fromCharCode", "fromCodePoint", "raw")}}
- -

Metode umum String

- -

Metode benda String juga terdapat dalam Firefox sejak JavaScript 1.6 (meskipun bukan bagian dari standar ECMAScript) salam objek String untuk menerapkan metode String ke objek lain:

- -
var num = 15;
-console.log(String.replace(num, /5/, '2'));
-
- -

{{jsxref("Global_Objects/Array", "Metode umum", "#Metode_umum_Array", 1)}} juga terdapat dalam metode {{jsxref("Global_Objects/Array", "Array")}}.

- -

Berikut ini sebuah pengisi untuk memberikan dukungan ke peramban yang tidak mendukung:

- -
/*globals define*/
-// Menganggap semua metode String telah ada
-(function() {
-  'use strict';
-
-  var i,
-    methods = [
-      'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
-      'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
-      'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
-      'toLocaleUpperCase', 'localeCompare', 'match', 'search',
-      'replace', 'split', 'substr', 'concat', 'slice'
-    ],
-    methodCount = methods.length,
-    assignStringGeneric = function(methodName) {
-      var method = String.prototype[methodName];
-      String[methodName] = function(arg1) {
-        return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
-      };
-    };
-
-  for (i = 0; i < methodCount; i++) {
-    assignStringGeneric(methods[i]);
-  }
-}());
-
- -

Benda String

- -

Properti

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properti')}}
- -

Metode

- -

Metode yang tidak terkait dengan HTML

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Metode_yang_tidak_terkait_dengan_HTML')}}
- -

Metode pembungkus HTML

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Metode_pembungkus_HTML')}}
- -

Contoh

- -

Contoh: Pengubahan String

- -

Ini mungkin untuk menggunakan String sebagai alternatif "lebih aman" dari {{jsxref("String.prototype.toString()", "toString()")}}, meskipun masih dapat secara normal memanggil toString(), ini juga bekerja untuk {{jsxref("Global_Objects/null", "null")}} dan {{jsxref("Global_Objects/undefined", "undefined")}}. Sebagai contoh:

- -
var outputStrings = [];
-for (var i = 0, n = inputValues.length; i < n; ++i) {
-  outputStrings.push(String(inputValues[i]));
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
ECMAScript 1st Edition.StandardDefinisi pertama.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
- -

Kompatibilitas peramban

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("0.2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown()}}{{CompatGeckoDesktop("40")}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("40")}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/indexof/index.html b/files/id/web/javascript/reference/global_objects/string/indexof/index.html deleted file mode 100644 index 3b7f7d0965..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/indexof/index.html +++ /dev/null @@ -1,190 +0,0 @@ ---- -title: String.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/String/indexOf -translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf ---- -
{{JSRef}}
- -

indexOf() method mengembalikan sebuah index saat memanggil objek  {{jsxref("String")}} pertama kali dengan value yang di tentukan, bermula dari pencarian pada fromIndex. Dan pencarian ini akan mengembalikan index dari karakter pada String,  dan akan mengembalikan -1 ketika pencarian indexOf ini tak menemukan karakter yang cocok/ value yang sesuai.

- -

Syntax

- -
str.indexOf(searchValue[, fromIndex])
- -

Parameters

- -
-
searchValue
-
Sebuah string yang me-representasikan dari nilai yang ingin di cari.
-
fromIndex {{optional_inline}}
-
Index bermulai dari awal hingga bergerak ke depan sepanjang string. Index bisa berupa bilangan bulat atau apa pun. Nilai standarnya adalah 0, jadi seluruh index dari array akan dicari. Jika fromIndex < 0 seluruh string dicari. Jika fromIndex >= str.length, string tidak dicari dan -1 sebagai kembaliannya. Kecuali kalau searchValue adalah string kosong, maka str.length sebagai kembaliannya.
-
- -

Deskripsi

- -

Karakter dalam sebuah string di indeks berurutan dari kiri ke kanan. Index pada karakter pertama yaitu 0, dan index pada karakter terakhir dalam sebuah String di sebut stringName is stringName.length - 1.

- -
'Blue Whale'.indexOf('Blue');     // mengembalikan  0
-'Blue Whale'.indexOf('Blute');    // mengembalikan -1
-'Blue Whale'.indexOf('Whale', 0); // mengembalikan  5
-'Blue Whale'.indexOf('Whale', 5); // mengembalikan  5
-'Blue Whale'.indexOf('', 9);      // mengembalikan  9
-'Blue Whale'.indexOf('', 10);     // mengembalikan 10
-'Blue Whale'.indexOf('', 11);     // mengembalikan 10
-
- -

Case-sensitivity

- -

The indexOf() method sangat case sensitive. Sebagai contoh, expression berikut ini mengembalikan -1:

- -
'Blue Whale'.indexOf('blue'); // mengembalikan -1
-
- -

Checking occurrences/ Memeriksa suatu kejadian

- -

Catat bahwa  '0' tak bernilai true dan '-1' bukan bernilali false. Oleh karena-nya, ketika memeriksa apakah sebuah String  Therefore, when checking if a specific string exists within another string the correct way to check would be:

- -
'Blue Whale'.indexOf('Blue') !== -1; // true
-'Blue Whale'.indexOf('Bloe') !== -1; // false
-
- -

Examples

- -

Using indexOf() and lastIndexOf()

- -

The following example uses indexOf() and {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} to locate values in the string "Brave new world".

- -
var anyString = 'Brave new world';
-
-console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
-// logs 8
-console.log('The index of the last w from the beginning is ' + anyString.lastIndexOf('w'));
-// logs 10
-
-console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
-// logs 6
-console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
-// logs 6
-
- -

indexOf() and case-sensitivity

- -

The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first {{domxref("console.log()")}} method displays 19. But because the indexOf() method is case sensitive, the string "cheddar" is not found in myCapString, so the second console.log() method displays -1.

- -
var myString    = 'brie, pepper jack, cheddar';
-var myCapString = 'Brie, Pepper Jack, Cheddar';
-
-console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'));
-// logs 19
-console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
-// logs -1
-
- -

Using indexOf() to count occurrences of a letter in a string

- -

The following example sets count to the number of occurrences of the letter e in the string str:

- -
var str = 'To be, or not to be, that is the question.';
-var count = 0;
-var pos = str.indexOf('e');
-
-while (pos !== -1) {
-  count++;
-  pos = str.indexOf('e', pos + 1);
-}
-
-console.log(count); // displays 4
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/length/index.html b/files/id/web/javascript/reference/global_objects/string/length/index.html deleted file mode 100644 index 6975d8b7d3..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/length/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: String.length -slug: Web/JavaScript/Reference/Global_Objects/String/length -translation_of: Web/JavaScript/Reference/Global_Objects/String/length ---- -
{{JSRef}}
- -

Properti length mewakili panjang string.

- -

Syntax

- -
str.length
- -

Deskripsi

- -

Properti ini mengembalikan jumlah unit kode dalam string. {{interwiki("wikipedia", "UTF-16")}}, Format string yang digunakan oleh javascript, Menggunakan 16-bit unit kode tunggal untuk mewakili karakter yang paling umum, tapi perlu menggunakan dua unit kode untuk unit karakter tertentu, sehingga dapat terjadi kemungkinan nilai yang dikembalikan oleh ​​​length tidak sesuai dengan jumlah karakter pada string.

- -

Untuk string kosong, jumlahnya 0.

- -

Properti static String.length mengembalikan nilai 1.

- -

Contoh

- -

Penggunaan Dasar

- -
var x = 'Mozilla';
-var kosong = '';
-
-console.log('Mozilla memiliki ' + x.length + ' unit kode');
-/* "Mozilla memiliki 7 unit kode" */
-
-console.log('String kosong memiliki jumlah unit kode ' + kosong.length);
-/* "String kosong memiliki jumlah unit kode 0" */
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi Inisial. Diimplementasikan dalam JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/link/index.html b/files/id/web/javascript/reference/global_objects/string/link/index.html deleted file mode 100644 index 914eff9955..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/link/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: String.prototype.link() -slug: Web/JavaScript/Reference/Global_Objects/String/link -tags: - - JavaScript - - Method - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/link ---- -
{{JSRef}}
- -

Method link() membuat sebuah string seperti halnya kode untuk sebuah elemen HTML {{HTMLElement("a")}} untuk digunakan sebagai link hypertext ke URL lain.

- -

Sintaks

- -
str.link(url)
- -

Parameters

- -
-
url
-
String yang menentukan atribut href dai tag <a>; harus merupakan URL yang valid (relative ataupun absolute), dengan setiap karakter & harus ditulis &amp;, dan setiap karakter " harus ditulis &quot;.
-
- -

Deskripsi

- -

Menggunakan method link() untuk membuat snippet HTML untuk sebuah link hypertext. Mengembalikan string  yang kemudian dapat di tambahkan ke dokumen html menggunakan {{domxref("document.write()")}} atau {{domxref("element.innerHTML")}}.

- -

Link yang dibuat menggunakan method link() akan menjadi elemen di array links dari sebuah objek document. Lihat juga {{domxref("document.links")}}.

- -

Contoh

- -

Penggunaan link()

- -

Pada contoh berikut menampilkan kata "MDN" sebagai sebuah link hypertext yang mengembalikan pengguna ke halaman Mozilla Developer Network.

- -
var hotText = 'MDN';
-var URL = 'https://developer.mozilla.org/';
-
-console.log('Klik untuk kembali ke ' + hotText.link(URL));
-// Klik untuk kembali ke <a href="https://developer.mozilla.org/">MDN</a>
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Catatan Gecko-specific

- - - -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/split/index.html b/files/id/web/javascript/reference/global_objects/string/split/index.html deleted file mode 100644 index 21f19d353f..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/split/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: String.prototype.split() -slug: Web/JavaScript/Reference/Global_Objects/String/split -tags: - - JavaScript - - Method - - Prototype - - Reference - - Regular Expressions - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/split ---- -
{{JSRef}}
- -

Method split() membagi sebuah objek {{jsxref("String")}} ke sebuah array string dengan memisahkannya menjadi substring.

- -

Sintaks

- -
str.split([separator[, limit]])
- -

Parameter

- -
-
separator
-
Opsional. Menentukan karakter yang digunakan untuk memisahkan string. separator dapat berupa string atau sebuah {{jsxref("Global_Objects/RegExp", "regular expression", "", 1)}}. Jika separator dihilangkan / tidak digunakan, array yang dikembalikan akan terdiri dari satu elemen yang berisi seluruh string. Jika separator dikosongkan atau empty string, str akan dikonversikan sebagai sebuah array dari karakter.
-
limit
-
-

Opsional. Nilai integer yang digunakan untuk menentukan jumlah batas yang dapat ditemukan. Method split() tetap membagi pada setiap kecocokan pada separator, sampai jumlah pembagi item sama dengan limit atau string jatuh lebih pendek dari separator.

-
-
- -

Deskripsi

- -

Method split() mengembalikan array baru.

- -

Saat ditemukan, separator akan dihapus dari string dan substrings akan di kembalikan ke dalam array. Jika separator tidak ditemukan atau di hilangkan, array terdiri satu elemen array yang terdiri dari keseluruhan string. Jika separator merupakan empty string, str dikonversi menjadi sebuah array karakter.

- -

Jika separator adalah ekspesi reguler yang terdapat tanda kurung , maka setiap kali separator cocok, hasilnya (termasuk hasil yang tidak didefinisikan) dari penangkap tanda kurung akan di sambungkan ke dalam output array. Namun, tidak semua browser mendukung kemampuan ini.

- -

{{Note("Ketika string kosong, method split() mengembalikan array berisi satu string kosong, dari pada array kosong. Jika string dan separator keduanya string kosong, array kosong akan dikembalikan.")}}

- -

Contoh

- -

Penggunaan split()

- -

Contoh berikut menjelaskan fungsi yang membagi string ke dalam sebuah array string menggunakan separator tertentu. Setelah memisahkan string , fungsi menampilkan pesan yang menunjukan string asli (sebelum dibagi), separator yang digunakan, jumlah elemen pada array, dan elemen array secara individual.

- -
function splitString(stringToSplit, separator) {
-  var arrayOfStrings = stringToSplit.split(separator);
-
-  console.log('The original string is: "' + stringToSplit + '"');
-  console.log('The separator is: "' + separator + '"');
-  console.log('The array has ' + arrayOfStrings.length + ' elements: ' + arrayOfStrings.join(' / '));
-}
-
-var tempestString = 'Oh brave new world that has such people in it.';
-var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';
-
-var space = ' ';
-var comma = ',';
-
-splitString(tempestString, space);
-splitString(tempestString);
-splitString(monthString, comma);
-
- -

Contoh ini menghasilkan output berikut:

- -
The original string is: "Oh brave new world that has such people in it."
-The separator is: " "
-The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.
-
-The original string is: "Oh brave new world that has such people in it."
-The separator is: "undefined"
-The array has 1 elements: Oh brave new world that has such people in it.
-
-The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
-The separator is: ","
-The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
-
- -

Menghapus spasi dari string

- -

Pada contoh berikut, split() mencari 0 atau lebih spasi diikuti semikolon, dan di ikuti 0 atau lebih spasi dan, saat ditemukan, menghapus spasi dari string. nameList merupakan array yang dikembalikan dari hasil split().

- -
var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';
-
-console.log(names);
-
-var re = /\s*;\s*/;
-var nameList = names.split(re);
-
-console.log(nameList);
-
- -

Dua baris log ini; log baris pertama string asli, dan log baris kedua array yang dihasilkan.

- -
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
-[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand " ]
-
- -

Mengembalikan batas jumlah pembagi

- -

Pada contoh berikut, split() mencari 0 atau lebih spasi didalam string dan mengembalikan 3 pembagian pertama yang ditemukan.

- -
var myString = 'Hello World. How are you doing?';
-var splits = myString.split(' ', 3);
-
-console.log(splits);
-
- -

Script ini akan menampilkan seperti berikut:

- -
Hello,World.,How
-
- -

Tanda kurung

- -

Jika separator terdapat tanda kurung, hasil yang cocok akan dikembalikan ke dalam array.

- -
var myString = 'Hello 1 word. Sentence number 2.';
-var splits = myString.split(/(\d)/);
-
-console.log(splits);
-
- -

Script tersebut menampilkan seperti berikut:

- -
[ 'Hello ', '1', ' word. Sentence number ', '2', '.' ]
-
- -

Membalikkan String menggunakan split()

- -
var str = 'asdfghjkl';
-var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
-// split() returns an array on which reverse() and join() can be applied
-
- -

Bonus: Gunakan operator {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} untuk mengetahui apakah string asli adalah palindrome.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
- - - - - - - -
Dukungan dasar 
-
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html deleted file mode 100644 index 69fdfd1bec..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: String.prototype.toLowerCase() -slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase -tags: - - JavaScript - - Method - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase ---- -
{{JSRef}}
- -

Method toLowerCase() mengembalikan nilai string yang dipanggil yang telah dikonversi ke lowercase (huruf kecil).

- -

Sintaks

- -
str.toLowerCase()
- -

Deskripsi

- -

Method toLowerCase() mengembaikan nilai dari string yang telah dikonversi ke lowercase. toLowerCase() tidak berdampak pada nilai string pada variabel str itu sendiri.

- -

Contoh

- -

Penggunaan toLowerCase()

- -
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/tostring/index.html b/files/id/web/javascript/reference/global_objects/string/tostring/index.html deleted file mode 100644 index dba9c9f792..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/tostring/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: String.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/String/toString -translation_of: Web/JavaScript/Reference/Global_Objects/String/toString ---- -
{{JSRef}}
- -

Method toString() mengembalikan sebuah string berdasarkan objek spesifik.

- -

Sintaks

- -
str.toString()
- -

Deskripsi

- -

Objek {{jsxref("String")}} akan menimpa method toString() dari objek {{jsxref("Object")}}; bukan turunan {{jsxref("Object.prototype.toString()")}}. Untuk objek {{jsxref("String")}}, method toString() mengembalikan sebuah string berdasarkan objek dan seperti halnya pada method {{jsxref("String.prototype.valueOf()")}}.

- -

Contoh

- -

Penggunaan toString()

- -

Pada contoh menampilkan nilai string dari sebuah objek {{jsxref("String")}}:

- -
var x = new String('Halo Dunia');
-
-console.log(x.toString()); // logs 'Halo Dunia'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.2', 'String.prototype.toString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/touppercase/index.html b/files/id/web/javascript/reference/global_objects/string/touppercase/index.html deleted file mode 100644 index bf8182a590..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/touppercase/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: String.prototype.toUpperCase() -slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase -translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase ---- -
{{JSRef}}
- -

Method toUpperCase() mengembalikan nilai string pemanggil dikonversi ke huruf besar.

- -

Sintaks

- -
str.toUpperCase()
- -

Deskripsi

- -

Method toUpperCase() mengembalikan nilai string diconversikan ke huruf besar. toUpperCase() tidak mempengaruhi nilai string itu sendiri.

- -

Contoh

- -

Penggunaan toUpperCase()

- -
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Pula

- - diff --git a/files/id/web/javascript/reference/global_objects/typedarray/index.html b/files/id/web/javascript/reference/global_objects/typedarray/index.html deleted file mode 100644 index e0b8d942c1..0000000000 --- a/files/id/web/javascript/reference/global_objects/typedarray/index.html +++ /dev/null @@ -1,344 +0,0 @@ ---- -title: TypedArray -slug: Web/JavaScript/Reference/Global_Objects/TypedArray -tags: - - JavaScript - - NeedsTranslation - - TopicStub - - TypedArray - - TypedArrays -translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray ---- -
{{JSRef}}
- -

A TypedArray object describes an array-like view of an underlying binary data buffer. There is no global property named TypedArray, nor is there a directly visible TypedArray constructor.  Instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. On the following pages you will find common properties and methods that can be used with any typed array containing elements of any type.

- -

Syntax

- -
new TypedArray(length);
-new TypedArray(typedArray);
-new TypedArray(object);
-new TypedArray(buffer [, byteOffset [, length]]);
-
-where TypedArray() is one of:
-
-Int8Array();
-Uint8Array();
-Uint8ClampedArray();
-Int16Array();
-Uint16Array();
-Int32Array();
-Uint32Array();
-Float32Array();
-Float64Array();
-
- -

Parameters

- -
-
length
-
When called with a length argument, a typed array containing length zeroes is created.
-
typedArray
-
When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array.
-
object
-
When called with an object argument, a new typed array is created as if by the TypedArray.from() method.
-
buffer, byteOffset, length
-
When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified {{jsxref("ArrayBuffer")}}. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view.  If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed.
-
- -

Description

- -

ECMAScript 6 defines a TypedArray constructor that serves as the [[Prototype]] of all TypedArray constructors.  This constructor is not directly exposed: there is no global %TypedArray% or TypedArray property.  It is only directly accessible through Object.getPrototypeOf(Int8Array.prototype) and similar.  All TypedArrays constructors inherit common properties from the %TypedArray% constructor function.  Additionally, all typed array prototypes (TypedArray.prototype) have %TypedArray%.prototype as their [[Prototype]].

- -

The %TypedArray% constructor on its own is not particularly useful.  Calling it or using it in a new expression will throw a TypeError, except when used during object creation in JS engines that support subclassing.  There are at present no such engines, so %TypedArray% is only useful to polyfill functions or properties onto all TypedArray constructors.

- -

Property access

- -

You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the {{jsxref("ArrayBuffer")}} and will never look at object properties. You can still use named properties, just like with all objects.

- -
// Setting and getting using standard array syntax
-var int16 = new Int16Array(2);
-int16[0] = 42;
-console.log(int16[0]); // 42
-
-// Indexed properties on prototypes are not consulted (Fx 25)
-Int8Array.prototype[20] = "foo";
-(new Int8Array(32))[20]; // 0
-// even when out of bound
-Int8Array.prototype[20] = "foo";
-(new Int8Array(8))[20]; // undefined
-// or with negative integers
-Int8Array.prototype[-1] = "foo";
-(new Int8Array(8))[-1]; // undefined
-
-// Named properties are allowed, though (Fx 30)
-Int8Array.prototype.foo = "bar";
-(new Int8Array(32)).foo; // "bar"
- -

TypedArray objects

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeSize in bytesDescriptionWeb IDL typeEquivalent C type
{{jsxref("Int8Array")}}18-bit two's complement signed integerbyteint8_t
{{jsxref("Uint8Array")}}18-bit unsigned integeroctetuint8_t
{{jsxref("Uint8ClampedArray")}}18-bit unsigned integer (clamped)octetuint8_t
{{jsxref("Int16Array")}}216-bit two's complement signed integershortint16_t
{{jsxref("Uint16Array")}}216-bit unsigned integerunsigned shortuint16_t
{{jsxref("Int32Array")}}432-bit two's complement signed integerlongint32_t
{{jsxref("Uint32Array")}}432-bit unsigned integerunsigned longuint32_t
{{jsxref("Float32Array")}}432-bit IEEE floating point numberunrestricted floatfloat
{{jsxref("Float64Array")}}864-bit IEEE floating point numberunrestricted doubledouble
- -

Properties

- -
-
{{jsxref("TypedArray.BYTES_PER_ELEMENT")}}
-
Returns a number value of the element size for the different typed array objects.
-
TypedArray.length
-
Length property whose value is 3.
-
{{jsxref("TypedArray.name")}}
-
Returns the string value of the constructor name. E.g "Int8Array".
-
{{jsxref("TypedArray.@@species", "get TypedArray[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("TypedArray.prototype")}}
-
Prototype for the TypedArray objects.
-
- -

Methods

- -
-
{{jsxref("TypedArray.from()")}}
-
Creates a new typed array from an array-like or iterable object. See also {{jsxref("Array.from()")}}.
-
{{jsxref("TypedArray.of()")}}
-
Creates a new typed array with a variable number of arguments. See also {{jsxref("Array.of()")}}.
-
- -

TypedArray prototype

- -

All TypedArrays inherit from {{jsxref("TypedArray.prototype")}}.

- -

Properties

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Properties')}}

- -

Methods

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Methods')}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Defined as TypedArray and ArrayBufferView interface with typed array view types. Superseded by ECMAScript 6.
{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ES6')}}Initial definition in an ECMA standard. Specified behaviour for indexed and named properties. Specified that new is required.
{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(7.0)}}{{CompatGeckoDesktop("2")}}1011.65.1
Indexed properties not consulting prototype{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop("25")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Named properties{{CompatVersionUnknown}}{{CompatGeckoDesktop("30")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2{{CompatVersionUnknown}}
Indexed properties not consulting prototype{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{ CompatGeckoMobile("25") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} [1]
Named properties{{CompatUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("30") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("44") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] -1 and similar are not considered as indexed properties and therefore return the value of the prototype property.

- -

Compatibility notes

- -

Starting with ECMAScript 2015 (ES6), TypedArray constructors require to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling a TypedArray constructor as a function without new, will throw a {{jsxref("TypeError")}} from now on.

- -
var dv = Int8Array([1, 2, 3]);
-// TypeError: calling a builtin Int8Array constructor
-// without new is forbidden
- -
var dv = new Int8Array([1, 2, 3]);
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/typedarray/join/index.html b/files/id/web/javascript/reference/global_objects/typedarray/join/index.html deleted file mode 100644 index 84f328ae1b..0000000000 --- a/files/id/web/javascript/reference/global_objects/typedarray/join/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: TypedArray.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/TypedArray/join -tags: - - ECMAScript6 - - JavaScript - - Method - - Prototype - - TypedArray -translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/join ---- -
{{JSRef}}
- -

Method join() menggabungkan semua elemen dari array menjadi sebuah string. Alogaritma method ini memiliki kesamaan dengan {{jsxref("Array.prototype.join()")}}. TypedArray di sini merupakan salah datu typed array types.

- -

Sintaks

- -
typedarray.join([separator = ',']);
- -

Parameter

- -
-
separator
-
Opsional. Menentukan sebuah string untuk memisahkan setiap elemen. Separator perlu di konversi ke string jika dianggap penting. Jika dikosongkan, elemen array akan dipisahkan dengan tanda koma (",").
-
- -

Contoh

- -
var uint8 = new Uint8Array([1,2,3]);
-uint8.join();      // '1,2,3'
-uint8.join(' / '); // '1 / 2 / 3'
-uint8.join('');    // '123'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-%typedarray%.prototype.join', 'TypedArray.prototype.join')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.join', 'TypedArray.prototype.join')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop("37")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("37")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/index.html b/files/id/web/javascript/reference/index.html deleted file mode 100644 index 261b76a5b5..0000000000 --- a/files/id/web/javascript/reference/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Referensi JavaScript -slug: Web/JavaScript/Reference -tags: - - JavaScript -translation_of: Web/JavaScript/Reference ---- -
{{JsSidebar}}
- -

Laman ini merupakan bagian dari sesi JavaScript pada MDN yang berfungsi sebagai acuan mengenai bahasa pemrograman JavaScript. Pelajari lebih lanjut perihal acuan ini.

- -

Objek Global

- -

Bagian ini mendokumentasikan semua object standar built-in JavaScript, beserta method dan propertinya.

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects', 'Standard_objects_by_category')}}
- -

Pernyataan

- -

Bagian ini mendekumentasikan semua pernyataan dan deklarasi  JavaScript.

- -
{{page('/id/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
- -

Ungkapan dan operator

- -

Bagian ini mendokumentasikan semua ungkapan dan operator JavaScript .

- -
{{page('/id/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
- -

Fungsi

- -

Bagian ini mendokumentasikan tentang Fungsi JavaScrip dan penggunaanya untuk pengembangan aplikasi anda.

- - - -

Acuan tambahan

- - diff --git a/files/id/web/javascript/reference/lexical_grammar/index.html b/files/id/web/javascript/reference/lexical_grammar/index.html deleted file mode 100644 index 83e5696ccd..0000000000 --- a/files/id/web/javascript/reference/lexical_grammar/index.html +++ /dev/null @@ -1,670 +0,0 @@ ---- -title: Lexical grammar -slug: Web/JavaScript/Reference/Lexical_grammar -translation_of: Web/JavaScript/Reference/Lexical_grammar ---- -
{{JsSidebar("More")}}
- -

Halaman ini menjelaskan tata bahasa leksikal JavaScript. Teks sumber skrip JavaScript dipindai dari kiri ke kanan dan diubah menjadi urutan elemen masukan yang merupakan token, karakter kontrol, terminator baris, komentar atau whitespace. ECMAScript juga mendefinisikan kata kunci dan literal tertentu dan memiliki aturan untuk penyisipan titik koma secara otomatis untuk mengakhiri pernyataan.

- -

Karakter-karakter kontrol

- -

Karakter kontrol tidak memiliki representasi visual namun digunakan untuk mengendalikan interpretasi teks.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter kontrol format unicode
KodeNamaSingkatanDeskripsi
U+200CZero width non-joiner<ZWNJ>Ditempatkan di antara karakter untuk mencegah terhubung ke ligatur dalam bahasa tertentu (Wikipedia).
U+200DZero width joiner<ZWJ>Ditempatkan di antara karakter yang biasanya tidak terhubung agar karakter dapat dirender menggunakan bentuknya yang terhubung dalam bahasa tertentu. (Wikipedia).
U+FEFFByte order mark<BOM>Digunakan pada awal skrip untuk menandainya sebagai Unicode dan urutan byte teks (Wikipedia).
- -

White space

- -

Karakter whitespace meningkatkan keterbacaan teks sumber dan memisahkan token-token. Karakter ini biasanya tidak diperlukan untuk fungsionalitas kode. Alat minifikasi sering digunakan untuk membuang whitespace agar mengurangi jumlah data yang perlu ditransfer.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter whitespace
KodeNamaSingkatanDeskripsi -

Rangkaian pelolosan/Escape

-
U+0009Tabulasi karakter<HT>Tabulasi horisontal\t
U+000BTabulasi baris<VT>Tabulasi vertikal\v
U+000CForm feed<FF>Karakter kontrol pemecah halaman (Wikipedia).\f
U+0020Space<SP>Spasi normal 
U+00A0No-break space<NBSP>Spasi normal, tetapi tidak ada petunjuk dimana baris terputus. 
OthersOther Unicode space characters<USP>Spasi di Unicode on Wikipedia 
- -

Terminator baris

- -

Selain karakter whitespace, karakter terminator baris digunakan untuk meningkatkan keterbacaan teks sumber. Namun, dalam beberapa kasus, terminator baris dapat mempengaruhi eksekusi kode JavaScript karena ada beberapa tempat di mana mereka dilarang. Terminator baris juga mempengaruhi proses penyisipan titik koma otomatis. Terminator baris dicocokkan dengan kelas \s dalam regular expressions.

- -

Hanya kode Unicode berikut yang diperlakukan sebagai terminator baris di ECMAScript, karakter pemecah baris lainnya diperlakukan sebagai whitespace (misalnya, Next Line, NEL, U+0085 dianggap sebagai whitespace).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter terminator baris
KodeNamaSingkatanDeskripsiRangkaian pelolosan/escape 
U+000ALine Feed<LF>Karakter baris baru di sistem UNIX.\n
U+000DCarriage Return<CR>Karakter baris baru di Commodore dan sistem Mac awal.\r
U+2028Line Separator<LS>Wikipedia 
U+2029Paragraph Separator<PS>Wikipedia 
- -

Komentar

- -

Komentar digunakan untuk menambahkan petunjuk, catatan, saran, atau peringatan ke kode JavaScript. Hal ini dapat mempermudah membaca dan memahami. Mereka juga dapat digunakan untuk menonaktifkan kode agar tidak dieksekusi; Ini juga dapat menjadi alat debugging yang berharga.

- -

JavaScript memiliki dua cara untuk memberi komentar pada kodenya.

- -

Cara pertama adalah komentar //; Ini membuat semua teks yang mengikutinya pada baris yang sama menjadi sebuah komentar. Sebagai contoh:

- -
function komentar() {
-  // Ini adalah komentar JavaScript satu baris
-  console.log('Hello world!');
-}
-komentar();
-
- -

Cara kedua adalah komentar gaya  /* */ , yang jauh lebih fleksibel.

- -

Misalnya, Anda bisa menggunakannya dalam satu baris:

- -
function komentar() {
-  /* Ini adalah komentar JavaScript satu baris */
-  console.log('Hello world!');
-}
-komentar();
- -

Anda juga bisa membuat komentar beberapa baris, seperti ini:

- -
function komentar() {
-  /* Komentar ini merentang dalam beberapa baris. Perhatikan
-     bahwa kita tidak perlu mengakhir komentar sebelum selesai. */
-  console.log('Hello world!');
-}
-komentar();
- -

Anda juga bisa menggunakannya di tengah baris, jika Anda mau, meskipun ini bisa membuat kode Anda lebih sulit dibaca sehingga harus digunakan dengan hati-hati:

- -
function komentar(x) {
-  console.log('Hello ' + x /* menysipkan nilai dari x */ + ' !');
-}
-comment('world');
- -

Selain itu, Anda bisa menggunakannya untuk menonaktifkan kode agar tidak berjalan, dengan membungkus kode dalam komentar, seperti ini:

- -
function comment() {
-  /* console.log('Hello world!'); */
-}
-comment();
- -

Dalam hal ini, pemaggilan console.log() tidak pernah dikeluarkan, karena itu ada di dalam komentar. Sejumlah baris kode dapat dinonaktifkan dengan cara ini.

- -

Kata kunci

- -

Reserved keywords as of ECMAScript 2015

- - - -

Kata kunci akan datang yang dicadangkan

- -

Berikut ini disediakan sebagai kata kunci akan datang menurut spesifikasi ECMAScript. Mereka tidak memiliki fungsi khusus saat ini, namun mungkin pada beberapa waktu mendatang, sehingga tidak dapat digunakan sebagai pengidentifikasi.

- -

Selalu dicadangkan:

- - - -

Berikut ini hanya dicadangkan saat ditemukan dalam kode mode strict "ketat":

- - - -

Berikut ini hanya dicadangkan saat ditemukan dalam kode modul:

- - - -

Kata kunci standart lama yang masih dingunakan hingga sekarang

- -

Berikut adalah dicadankan sebagai kata kunci akan datang pada spesifikasi ECMAScript usang (ECMAScript 1 s/d 3).

- - - -

Selain itu literal-literal null, true, dan false tidak dapat digunakan sebagai pengidentifikasi didalam ECMAScript.

- -

Penggunaan kata dicadangkan

- -

Kata yang dicadangkan sebenarnya hanya berlaku untuk pengidentifikasi (vs. IdentifierNames ). Seperti yang dijelaskan di es5.github.com/#A.1, ini semua adalah IdentifierNames yang tidak mengecualikan ReservedWords .

- -
a.import
-a['import']
-a = { import: 'test' }.
-
- -

Di sisi lain, hal-hal berikut ini ilegal karena ini adalah pengidentifikasi, yaitu IdentifierName tanpa kata-kata yang dicadangkan. Pengidentifikasi digunakan untuk FunctionDeclaration dan FunctionExpression.

- -
function import() {} // Illegal.
- -

Literal

- -

Literal null

- -

Lihat juga null untuk informasi lebih lanjut.

- -
null
- -

Literal Boolean

- -

Lihat juga Boolean untuk informasi lebih lanjut.

- -
true
-false
- -

Literal numerik

- -

Decimal

- -
1234567890
-42
-
-// Waspada saat mengunakan nol dimuka:
-0888 // 888 diuraikan sebagai desimal
-0777 // diuraikan sebagai oktal, 511 dalam desimal
-
- -

Perhatikan bahwa literal desimal dapat dimulai dengan angka nol ( 0 ) diikuti oleh digit desimal lainnya, namun jika semua digit setelah angka 0 teratas lebih kecil dari 8, angka tersebut diartikan sebagai angka oktal. Ini tidak akan melempar JavaScript, lihat {{bug(957513)}}. Lihat juga halaman tentang parseInt().

- -

Biner

- -

Sintaksis bilangan biner menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "B" ( 0b atau 0B ). Karena sintaksis ini baru di ECMAScript 2015, lihat tabel kompatibilitas browser, di bawah ini. Jika digit setelah 0b tidak 0 atau 1, SyntaxError berikut dilempar: "Missing binary digits after 0b".

- -
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
-var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
-var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
- -

Oktal

- -

Sintaksis bilangan oktal menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "O" ( 0o atau 0O). Karena sintaks ini baru di ECMAScript 2015, lihat tabel kompatibilitas browser, di bawah ini. Jika digit setelah 0o berada di luar kisaran (01234567), SyntaxError berikut dilempar: "Missing octal digits after 0o".

- -
var n = 0O755; // 493
-var m = 0o644; // 420
-
-// Juga dimungkinkan hanya menggunakan nol dimuka (lihat tentang desimal diatas)
-0755
-0644
-
- -

Heksadesimal

- -

Sintaksis bilangan heksadesimal menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "X" ( 0x atau 0X). Jika digit setelah 0x berada di luar rentang (0123456789ABCDEF), SyntaxError berikut dilempar: "Identifier starts immediately after numeric literal".

- -
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
-0x123456789ABCDEF   // 81985529216486900
-0XA                 // 10
-
- -

Literal objek

- -

Lihat juga Objek and Penginisialisasi objek untuk informasi lebih lanjut.

- -
var o = { a: 'foo', b: 'bar', c: 42 };
-
-// notasi singkat. baru di ES2015
-var a = 'foo', b = 'bar', c = 42;
-var o = {a, b, c};
-
-// bukannya
-var o = { a: a, b: b, c: c };
-
- -

Literal array

- -

Lihat juga Array untuk informasi lebih lanjut.

- -
[1954, 1974, 1990, 2014]
- -

Literal string

- -
'foo'
-"bar"
- -

Rangkaian pelolosan/escape heksadesimal

- -
'\xA9' // "©"
-
- -

Rangkaian pelolosan/escape Unicode

- -

Rangkaian pelolosan Unicode memerlukan setidaknya empat karakter diawali \u.

- -
'\u00A9' // "©"
- -

Penerapan point kode Unicode

- -

Baru di ECMAScript 2015. Dengan pelolosan kode Unicode, tiap karakter dapat diloloskan menggunakan bilangan hexadesimal jadi dimungkinkan untuk menggunkan kode Unicode sampai 0x10FFFF. Dengan pelolosan Unicode sederhana terkadang lebih dibutuhkan untuk menulis bagian pengganti secara terpisah untuk mencapai tujuan yang sama.

- -

Lihat juga String.fromCodePoint() atau String.prototype.codePointAt().

- -
'\u{2F804}'
-
-// ekuivalen dengan pelolosan Unicode sederhana
-'\uD87E\uDC04'
- -

Literal regular expression

- -

Lihat juga RegExp untuk informasi lebih lanjut.

- -
/ab+c/g
-
-// Suatu literal "kosong" regular expression
-// diperlukan grup bukan penangkap
-// untuk menghindarkan ambiguitas denga komentar satu baris
-/(?:)/
- -

Literal template

- -

Lihat juga template strings untuk informasi lebih lanjut.

- -
`string text`
-
-`string text baris 1
- string text baris 2`
-
-`string text ${expression} string text`
-
-tag `string text ${expression} string text`
- -

Penyisipan titik koma otomatis

- -

Beberapa pernyataan JavaScript harus diakhiri dengan titik koma an oleh karena itu dipengaruhi oleh penyisipan otomatis semicolon (ASI):

- - - -

Spesifikasi ECMAScript menyebutkan tiga aturan penyisipan titik koma.

- -

1.  Titik koma disisipkan sebelumnya, bila terminator baris or "}" diteramukan yang tidak diizinkan oleh tata bahasa.

- -
{ 1 2 } 3
-
-// di transformasikan ke ASI kedalam
-
-{ 1 2 ;} 3;
- -

2.  Titik koma disisipkan di bagian akhir, saat akhir aliran input token terdeteksi dan parser tidak dapat mengurai aliran input tunggal aliran sebagai program yang lengkap.

- -

Disini ++ tidak diperlakukan sebagai operator postfix yang menerapkan variabel b, karena terminator baris terjadi antara b dan ++.

- -
a = b
-++c
-
-// di transformasikan ke ASI kedalam
-
-a = b;
-++c;
-
- -

3. Titik koma disisipkan pada akhirnya, ketika sebuah pernyataan dengan produksi terbatas dalam tata bahasa diikuti oleh terminator baris. Pernyataan-pernyataan ini dengan aturan "tidak diperlukan terminator baris" adalah:

- - - -
return
-a + b
-
-// di transformasikan ke ASI kedalam
-
-return;
-a + b;
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2("ES1")}}Definisi awal.
{{SpecName('ES5.1', '#sec-7', 'Lexical Conventions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ES6')}} -

Ditambahkan: Literal Bilangan Biner dan Octal, pelolosan kode Unicode, Templates

-
{{SpecName('ESDraft', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Literal numerik biner dan oktal (0b dan 0o){{CompatChrome(41)}}12{{CompatGeckoDesktop(25)}}{{CompatUnknown}}{{CompatOpera(28)}}{{CompatSafari(9)}}
Pelolosan kode Unicode (\u{}){{CompatChrome(44)}}12{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatOpera(31)}}{{CompatSafari(9)}}
Notasi singkat untuk literal objek{{CompatChrome(43)}}12{{CompatGeckoDesktop(33)}}{{CompatNo}}{{CompatChrome(30)}}{{CompatSafari(9)}}
Literal template{{CompatChrome(41)}}12{{CompatGeckoDesktop(34)}}{{CompatNo}}{{CompatOpera(28)}}{{CompatSafari(9)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Literal numerik biner dan oktal (0b dan 0o){{CompatUnknown}}41{{CompatGeckomobile(33)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Pelolosan kode Unicode (\u{}){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckomobile(40)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Notasi singkat untuk literal objek{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(33)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Literal template{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(34)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Firefox-specific notes

- - - -

See also

- - diff --git a/files/id/web/javascript/reference/operators/conditional_operator/index.html b/files/id/web/javascript/reference/operators/conditional_operator/index.html deleted file mode 100644 index 1a64158acb..0000000000 --- a/files/id/web/javascript/reference/operators/conditional_operator/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Operasional Kondisi (ternary) -slug: Web/JavaScript/Reference/Operators/Conditional_Operator -translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator ---- -
{{jsSidebar("Operators")}}
- -

Operasianal kondisional (ternary) adalah satu-satunya operator yang hanya membutuhkan tiga operator. Operator ini sering digunakan sebagai jalan pintas untuk `if` statement.

- -

Syntax

- -
condition ? expr1 : expr2 
- -

Parameters

- -
-
condition (atau conditions)
-
Sebuah ekspresi akan menguji apakah menghasilkan true atau false.
-
- -
-
expr1, expr2
-
Ekspresi yang akan dilakukan setelah kondisi terpenuhi.
-
- -

Description

- -

Jika condition menghasilkan true, maka operator ini akan menghasilkan/mengembalikan nilai dari expr1; dan jika sebaliknya, ini akan menghasilkan/mengembalikan nilai dari expr2. Sebagai contoh, untuk menampilkan pesan yang berbeda berdasarkan nilai dari variabel isMember, anda bisa menggunakan contoh kode berikut:

- -
var isMember = true;
-'The fee is ' + (isMember ? '$2.00' : '$10.00'); //$2.00
-
- -

Anda juga dapat mendefinisikan sebuah variabel secara langsung:

- -
var elvisLives = Math.PI > 4 ? 'Yep' : 'Nope';
- -

Anda juga bisa menggunakan operator ternary secara jamak (catatan: conditional operator adalah associative yang lebih baik):

- -
var firstCheck = false, secondCheck = false, access = firstCheck ? 'Access denied' : secondCheck ? 'Access denied' : 'Access granted';
-console.log(access); // logs "Access granted"
- -

Anda juga dapat menggunakan pengondisian jamak seperti pengondisian jamak pada statement IF pada umumnya:

- -
var condition1 = true,
-    condition2 = false,
-    access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
-
-console.log(access); // logs "true false"
-
- -

 

- -

Note: The parentheses are not required, and do not affect the functionality. They are there to help visualize how the outcome is processed.

- -

You can also use ternary evaluations in free space in order to do different operations:

- -
var stop = false, age = 16;
-
-age > 18 ? location.assign('continue.html') : stop = true;
-
- -

You can also do more than one single operation per case, separating them with a comma, and enclosing them in parenthesis:

- -
var stop = false, age = 23;
-
-age > 18 ? (
-    alert('OK, you can go.'),
-    location.assign('continue.html')
-) : (
-    stop = true,
-    alert('Sorry, you are much too young!')
-);
-
- -

You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned.

- -
var age = 16;
-
-var url = age > 18 ? (
-    alert('OK, you can go.'),
-    // alert returns "undefined", but it will be ignored because
-    // isn't the last comma-separated value of the parenthesis
-    'continue.html' // the value to be assigned if age > 18
-) : (
-    alert('You are much too young!'),
-    alert('Sorry :-('),
-    // etc. etc.
-    'stop.html' // the value to be assigned if !(age > 18)
-);
-
-location.assign(url); // "stop.html"
- -

Returning Ternary Statements

- -

The ternary operator lends itself well to function returns that would otherwise require an if/else statement.

- -
var func1 = function( .. ) {
-  if (condition1) { return value1 }
-  else { return value2 }
-}
-
-var func2 = function( .. ) {
-  return condition1 ? value1 : value2
-}
- -

A good way to spot that the ternary will be a suitable replacement for an if/else statement is when the return keyword is used multiple times and is the only expression inside of the if block.

- -

By breaking the ternary onto multiple lines and making use of extra whitespace, the ternary operator can be used to very cleanly replace a lengthy series of if/else statements. This provides a syntactically light way of expressing the same logic:

- -
var func1 = function( .. ) {
-  if (condition1) { return value1 }
-  else if (condition2) { return value2 }
-  else if (condition3) { return value3 }
-  else { return value4 }
-}
-
-var func2 = function( .. ) {
-  return condition1 ? value1
-       : condition2 ? value2
-       : condition3 ? value3
-       :              value4
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.conditional")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/operators/function/index.html b/files/id/web/javascript/reference/operators/function/index.html deleted file mode 100644 index 7fa9564333..0000000000 --- a/files/id/web/javascript/reference/operators/function/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: ungkapan fungsi -slug: Web/JavaScript/Reference/Operators/function -tags: - - Fungsi - - JavaScript - - Operator - - Ungkapan Utama -translation_of: Web/JavaScript/Reference/Operators/function -original_slug: Web/JavaScript/Reference/Operators/fungsi ---- -
{{jsSidebar("Operators")}}
- -
Kata kunci fungsi digunakan untuk mendefinisikan fungsi dalam sebuah ungkapan.
- -
 
- -

Sintaksis

- -
function [nama]([param1[, param2[, ..., paramN]]]) {
-   pernyataan
-}
- -

Parameters

- -
-
nama
-
Bisa dihilangkan apabila fungsi merupaka fungsi anonim. Nama fungsi bersifat lokal, relatif terhadap tubuh fungsi.
-
paramN
-
Nama argumen yang akan diumpankan kepada fungsi.
-
pernyataan
-
Pernyataan yang menyusun tubuh fungsi.
-
- -

Deskripsi

- -

Sintaksis ungkapan fungsi nyaris sama apabila dibandingkan dengan sintaksis pernyataan fungsi(lihat pernyataan fungsi untuk lebih jelasnya). Perbedaan utama antara ungkapan fungsi dengan pernyataan fungsi ialah; ungkapan fungsi memperbolehkan nama fungsi untuk tidak digunakan/dihilangkan apabila ungkapan fungsi tersebut merupakan fungsi anonim. Ungkapan fungsi dapat digunakan sebagai IIFE (immediately Invoked Function Expression), sebuah fungsi yang otomatis dijalankan apabila didefinisikan. Untuk informasi lebih lanjut, lihat juga bab tentang fungsi.

- -

Contoh

- -

Dibawah ini merupakan contoh definisi sebuah fungsi tanpa nama yang kemudian ditugaskan kedalam variabel x:

- -
var x = function(y) {
-   return y * y;
-};
-
- -

Ungkapan fungsi bernama (Named function expression)

- -

Apabila sebuah fungsi hendak dipanggil dari dalam tubuh fungsi itu sendiri, pergunakanlah ungkapan fungsi bernama. Nama fungsi bersifat lokal relatif terhadap tubuh fungsi. Manfaat penggunaan ungkapan fungsi bernama ialah menghindarkan penggunaan properti non-standar arguments.callee.

- -
var math = {
-  'factorial': function factorial(n) {
-    if (n <= 1)
-      return 1;
-    return n * factorial(n - 1);
-  }
-};
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}}Definisi awal. Diterapkan pada JavaScript 1.5.
- -

Kesesuaian Perambah (Browser)

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Mendasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Mendasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/operators/index.html b/files/id/web/javascript/reference/operators/index.html deleted file mode 100644 index ef3afeb763..0000000000 --- a/files/id/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,269 +0,0 @@ ---- -title: Expressions and operators -slug: Web/JavaScript/Reference/Operators -tags: - - JavaScript - - NeedsTranslation - - Operators - - TopicStub -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -

This chapter documents all the JavaScript language operators, expressions and keywords.

- -

Ekspresi and operator sesuai kategori

- -

Untuk daftar isi sesuai Alfabet, silahkan lihat sisi sebelah kiri artikel ini.

- -

Primary expressions

- -

Basic keywords and general expressions in JavaScript.

- -

Keyword-keyword dasar dan ekspersi-ekspresi umum di javascript

- -
-
{{jsxref("Operators/this", "this")}}
-
The this keyword refers to the function's execution context.
-
{{jsxref("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{jsxref("Global_Objects/Array", "[]")}}
-
Array literal syntax.
-
{{jsxref("Global_Objects/Object", "{}")}}
-
Object literal syntax.
-
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{experimental_inline()}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{experimental_inline()}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
{{jsxref("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Left-hand-side expressions

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
{{experimental_inline()}} {{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{experimental_inline()}} {{jsxref("Operators/Spread_operator", "...obj")}}
-
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
-
- -

Increment and decrement

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Unary operators

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

Arithmetic operators

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -

Relational operators

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -

Equality operators

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Binary bitwise operators

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Binary logical operators

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Conditional (ternary) operator

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Assignment operators

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{experimental_inline()}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{experimental_inline()}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

-
-
- -

Comma operator

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
-

The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.

-
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
- -

See also

- - diff --git a/files/id/web/javascript/reference/operators/yield/index.html b/files/id/web/javascript/reference/operators/yield/index.html deleted file mode 100644 index 366f2aaa38..0000000000 --- a/files/id/web/javascript/reference/operators/yield/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: yield -slug: Web/JavaScript/Reference/Operators/yield -translation_of: Web/JavaScript/Reference/Operators/yield ---- -
{{jsSidebar("Operators")}}
- -

Keyword yield digunakan untuk menghentikan sementara dan melanjutkan sebuah fungsi generator ({{jsxref("Statements/function*", "function*")}} atau legacy generator function).

- -

Sintak

- -
[rv] = yield [expression];
- -
-
expression
-
Mendefeniskan nilai yang akan dikembalikan melalui iterator protocol. Apabila diabaikan, maka undefined akan dikembalikan.
-
rv
-
-

Mengembalikan nilai opsional yang diberikan pada generator method next() untuk melanjutkan eksekusinya.

-
-
- -

Deskripsi

- -

Keyword yield menghentikan secara sementara eksekusi dari fungsi generator dan nilai setelah keyword yield dikembalikan pada pemanggil generator tersebut. yield bisa juga disebut sebagai versi generator dari keywordreturn.

- -

Keyword yield sebenarnya mengembalikan sebuah obyek IteratorResult dengan dua properti, value dan done. Propertivalue adalah hasi dari evaluasi ekspresi yield, dan done yang false, mengindikasikan bahwa fungsi generator tersebut belum selesai sepenuhnya.

- -

Sekali berhenti pada ekspresi yield , eksekusi dari code generator tersebut akan terus dihentikan sampai generator method next() dipanggil. Setiap kali method generator next() dipanggil, generator melanjutkan eksekusi dan berjalan hingga mencapai salah satu dari kondisi berikut ini :

- - - -

JIka sebuah nilai opsional diberikan pada generator method next(), nilai tersebut menjadi nilai yang dikembalikan oleh operasi yield dari generator pada saat itu.

- -

Di antara kode generator, operatoryield -nya, dan kemampuan untuk menentukan sebua nilai awal baru dengan memberikannya pada {{jsxref("Generator.prototype.next()")}}, generator menawarkan power dan kontrol yang luar biasa.

- -

Contoh

- -

Kode berikut merupakan deklarasi dari sebuah contoh fungsi generator.

- -
function* countAppleSales () {
-  var saleList = [3, 7, 5];
-  for (var i = 0; i < saleList.length; i++) {
-    yield saleList[i];
-  }
-}
- -

Setelah sebuah fungsi generator didefenisikan, maka fungsi tersebut dapat digunakan untuk menghasilkan sebuah iterator seperti berikut.

- -
var appleStore = countAppleSales(); // Generator { }
-console.log(appleStore.next()); // { value: 3, done: false }
-console.log(appleStore.next()); // { value: 7, done: false }
-console.log(appleStore.next()); // { value: 5, done: false }
-console.log(appleStore.next()); // { value: undefined, done: true }
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES2015', '#', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}}{{Spec2('ESDraft')}}
- -

Kompatabilitas Browser

- - - -

{{Compat("javascript.operators.yield")}}

- -

Catatan Firefox-specific

- - - -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/class/index.html b/files/id/web/javascript/reference/statements/class/index.html deleted file mode 100644 index 6ca35e9c71..0000000000 --- a/files/id/web/javascript/reference/statements/class/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: class -slug: Web/JavaScript/Reference/Statements/class -tags: - - Classes - - Declaration - - ECMAScript6 - - Referensi -translation_of: Web/JavaScript/Reference/Statements/class ---- -
{{jsSidebar("Statements")}}
- -

Deklarasi class digunakan untuk membuat class baru dengan nama menggunakan turunan berbasis prototype.

- -
-

Anda juga bisa mendefinisikan kelas menggunakan{{jsxref("Operators/class", "class expression", "", 1)}}.

-
- -

Sintaks

- -
class name [extends] {
-  // class body
-}
-
- -

Deskripsi

- -

Seperti halnya dengan ekspresi class,  pembentuk (body) class dari deklarasi class di jalankan pada strict mode.

- -

Deklarasi class bukanlah {{Glossary("Hoisting", "hoisted")}} (Tidak seperti function declarations).

- -

Contoh

- -

Dasar deklarasi class

- -

Pada contoh, hal pertama yang kita lakukan adalah mendefinisikan class dengan nama Polygon, kemudian membentangkannya ( extend ) untuk membuat class bernama Square. Perlu diperhatikan bahwa super(), digunakan pada constructor, hanya dapat digunakan di konstruktor dan harus dipanggil setelah keyword 'this' dapat digunakan.

- -
class Polygon {
-  constructor(height, width) {
-    this.name = 'Polygon';
-    this.height = height;
-    this.width = width;
-  }
-}
-
-class Square extends Polygon {
-  constructor(length) {
-    super(length, length);
-    this.name = 'Square';
-  }
-}
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Array subclassing{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Allowed in sloppy mode{{CompatChrome(49.0)}}    
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Array subclassing{{CompatNo}}{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
Allowed in sloppy mode{{CompatNo}}{{CompatChrome(49.0)}}    {{CompatChrome(49.0)}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/statements/do...while/index.html b/files/id/web/javascript/reference/statements/do...while/index.html deleted file mode 100644 index 01c518ad84..0000000000 --- a/files/id/web/javascript/reference/statements/do...while/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: do...while -slug: Web/JavaScript/Reference/Statements/do...while -tags: - - JavaScript - - Referensi -translation_of: Web/JavaScript/Reference/Statements/do...while ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan do...while digunakan untuk membuat perulangan yang mengeksekusi penyataan tertentu hingga kondisi pemeriksaan penyataan tersebut bernilai false. Kondisi akan diperiksa setelah pernyataan dieksekusi/dijalankan dengan hasil penyataan tersebut yang dijalankan sekurangnya sekali.

- -
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
- - - -

Sintaks

- -
do
-   penyataan
-while (kondisi);
-
- -
-
penyataan
-
Sebuah penyataan yang dieksekusi setidaknya sekali dan akan kembali dieksekusi setiap kali kondisi pemeriksaan bernial true. Untuk mengeksekusi lebih dari satu penyataan di dalam perulangan, gunakan pernyataan {{jsxref("Statements/block", "block")}}  ({ ... }) untuk mengelompokkan penyataan.
-
- -
-
kondisi
-
Sebuah ekspresi yang periksa setelah perulangan. Bila kondisi periksa bernilai true, maka pernyataan akan kembali dieksekusi. Bila kondisi periksa bernilai false, maka kendali akan melewati do...while dan meneruskan ke pernyataan selanjutnya.
-
- -

Contoh

- -

Penggunaan do...while

- -

Pada contoh berikut, perulangan do...while diiterasikan setidaknya sekali dan kembali di iterasikan sampai nilai i tidak kurang dari 5.

- -

Kode HTML

- -
<div id="example"></div>
- -

Kode JavaScript

- -
var result = '';
-var i = 0;
-do {
-   i += 1;
-   result += i + ' ';
-} while (i < 5);
-document.getElementById('example').innerHTML = result;
- -

Hasil

- -

{{ EmbedLiveSample('Examples') }}

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.6.1', 'do-while statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ES6')}}Trailing ; is now optional.
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas Peramban

- - - -

{{Compat("javascript.statements.do_while")}}

- -

Lihat pula

- - diff --git a/files/id/web/javascript/reference/statements/empty/index.html b/files/id/web/javascript/reference/statements/empty/index.html deleted file mode 100644 index 26b2bf8d20..0000000000 --- a/files/id/web/javascript/reference/statements/empty/index.html +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: empty -slug: Web/JavaScript/Reference/Statements/Empty -tags: - - JavaScript - - Statement -translation_of: Web/JavaScript/Reference/Statements/Empty ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan empty digunakan untuk menyediakan statement kosong, walaupun begitu sintaks JavaScript tetap menghitungnya sebagai sebuah Pernyataan.

- -

Sintak

- -
;
-
- -

Deskripsi

- -

Statemen atau penyataan kosong hanya berupa semicolon (;) menunjukkan bahawa tidak ada statement untuk dijalankan, meskipun jika sintak JavaScript membutuhkan salah satunya. Sifat kebalikan, dimana anda ingin menggunakan lebih dari satu statemen, namun javascript hanya memperbolehkan sebuah statemen kosong, anda bisa menggunakan block statement; yang merupakan gabungan dari beberapa statement menjadi satu.

- -

Contoh

- -

Statement kosong terkadang digunakan pada perulangan. Lihat pada contoh dengan body berisi sebuah statement kosong:

- -
var arr = [1, 2, 3];
-
-// Assign all array values to 0
-for (i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
-
-console.log(arr)
-// [0, 0, 0]
-
- -

Catatan: Ini merupakan ide yang bagus dengan menggunakan komentar pada penggunaan statement kosong, karena ini tidak benar - benar jelas seperti halnya penggunaan semicolon (;) pada umumnya. Contoh berikut bisa dikatakan merupakan penggunaan yang tidak disengaja:

- -
if (condition);       // Perhatian, "if" tidak menjalankan apapun!
-   killTheUniverse()  // Jadi ini akan selalu di jalankan!!!
-
- -

Contoh lain: Statemen if...else tanpa tanda kurung keriting ({}). Jika three bernilai true, tidak akan terjadi apapun, four tidak begitu penting, dan juga fungsi launchRocket() pada kasus else tidak akan dijalankan.

- -
if (one)
-  doOne();
-else if (two)
-  doTwo();
-else if (three)
-  ; // nothing here
-else if (four)
-  doFour();
-else
-  launchRocket();
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.3', 'Empty statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES1')}}Initial definition.
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/export/index.html b/files/id/web/javascript/reference/statements/export/index.html deleted file mode 100644 index 1f6d26b71d..0000000000 --- a/files/id/web/javascript/reference/statements/export/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: export -slug: Web/JavaScript/Reference/Statements/export -translation_of: Web/JavaScript/Reference/Statements/export ---- -
{{jsSidebar("Statements")}}
- -

export statement digunakan untuk meng-ekspor fungsi, objects atau primitives dari file yang di berikan (atau module).

- -
-

Catatan: Fitur ini tidak di implementasikan di browser secara bawaan untuk saat ini. ini hanya diimplementasikan di beberapa transpilers, seperti Traceur CompilerBabel atau Rollup.

-
- -

Syntax

- -
export { name1, name2, …, nameN };
-export { variable1 as name1, variable2 as name2, …, nameN };
-export let name1, name2, …, nameN; // also var
-export let name1 = …, name2 = …, …, nameN; // also var, const
-
-export default expression;
-export default function (…) { … } // also class, function*
-export default function name1(…) { … } // also class, function*
-export { name1 as default, … };
-
-export * from …;
-export { name1, name2, …, nameN } from …;
-export { import1 as name1, import2 as name2, …, nameN } from …;
- -
-
nameN
-
- -

Identitas yang akan diekspor ( sehingga dapat di impor via import di lain skrip).

- -

Deskripsi

- -

Ada dua jenis tipe yang berbeda-beda dari export, masing-masing sesuai dengan salah satu sintaks di atas:

- - - -

Named exports berguna untuk mengekspor beberapa nilai. Selama import, satu akan menggunakan nama yang sama untuk mengacu pada nilai yang sesuai.

- -

Mengenai default export, hanya ada satu default export per modul. default export bisa menjadi fungsi, class, objek atau yang lainya. Nilai ini dianggap sebagai  "Pokok" pengeluaran nilai karena akan menjadi sederhana untuk di import.

- -

Contoh

- -

Menggunakan named exports

- -

dalam modul, kita bisa menggunakan kode berikut:

- -
// module "my-module.js"
-export function cube(x) {
-  return x * x * x;
-}
-const foo = Math.PI + Math.SQRT2;
-export { foo };
-
- -

Cara ini, di dalam script lain  (cf. import), kita bisa memiliki:

- -
import { cube, foo } from 'my-module';
-console.log(cube(3)); // 27
-console.log(foo);    // 4.555806215962888
- -

Menggunakan default export

- -

Jika kita ingin mengekspor nilai tunggal atau memiliki nilai fallback untuk modul kita, kita bisa menggunakan default export:

- -
// module "my-module.js"
-export default function cube(x) {
-  return x * x * x;
-}
-
- -

Kemudian, di lain skrip, akan lebih mudah untuk mengimpor export default :

- -
import cube from 'my-module';
-console.log(cube(3)); // 27
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-exports', 'Exports')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/for...in/index.html b/files/id/web/javascript/reference/statements/for...in/index.html deleted file mode 100644 index 0162c204ee..0000000000 --- a/files/id/web/javascript/reference/statements/for...in/index.html +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: for...in -slug: Web/JavaScript/Reference/Statements/for...in -tags: - - JavaScript - - Statement -translation_of: Web/JavaScript/Reference/Statements/for...in ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan for...in mengulang setiap properti enumerable dari sebuah objek, dalam urutan sembarang. Untuk setiap properti yang berbeda, pernyataan dapat dieksekusi.

- -

Sintak

- -
for (variable in object) {...
-}
- -
-
variable
-
Sebuah nama properti yang berbeda ditugaskan untuk variabel pada setiap iterasi.
-
object
-
Objek yang propertinya enumerable yang diiterasi.
-
- -

Deskripsi

- -

Perulangan for...in hanya mengiterasi pada properti enumerable. Objek yang dibuat dari built-in konstruktor seperti Array dan Object telah mewarisi properti non-enumerable dari Object.prototype dan String.prototype, seperti {{jsxref("String")}}'s {{jsxref("String.indexOf", "indexOf()")}} metode atau {{jsxref("Object")}}'s {{jsxref("Object.toString", "toString()")}} metode. Perulangan akan iterate atas semua properti enumerable dari objek itu sendiri dan mereka objek mewarisi dari prototipe konstruktor ini (properti lebih dekat ke objek di properti mata rantai prototipe menggantikan prototipe' properti).

- -

Penghapusan, penambahan atau perubahan pada properti

- -

Perulangan for...in mengiterasi properti suatu objek dalam urutan sembarang (lihat {{jsxref("Operators/delete", "delete")}} Operator untuk lebih lanjut tentang mengapa salah satu tidak dapat bergantung pada keteraturan tampak dari iterasi, setidaknya dalam pengaturan lintas-browser). Jika properti yang diubah dalam satu iterasi dan kemudian mengunjungi di lain waktu, nilainya dalam lingkaran adalah nilai pada waktu kemudian. Sebuah properti yang dihapus sebelum telah dikunjungi tidak akan dikunjungi nanti. Sifat ditambahkan ke objek dimana iterasi terjadi baik dapat dikunjungi atau dihilangkan dari iterasi. Secara umum yang terbaik adalah tidak untuk menambah, mengubah atau menghapus properti dari objek selama iterasi, selain properti saat ini sedang mengunjungi. Tidak ada jaminan apakah properti menambahkan akan dikunjungi, apakah properti dimodifikasi (selain yang saat ini) akan dikunjungi sebelum atau setelah dimodifikasi, atau apakah properti dihapus akan dikunjungi sebelum dihapus.

- -

Iterasi Array dan for...in

- -
-

Catatan: for...in tidak perlu digunakan untuk mengiterasi sebuah {{jsxref("Array")}} dimana urutan indeksnya sangat penting.

-
- -

Index array hanyalah properti enumerable dengan nama integer dan tidak sama dengan properti Objek pada umumnya. Disini tidak akan menjamin jika for...in akan mengembalikan indek pada urutan tertentu.  Pernyataan for...in akan mengembalikan semua properti enumerable, termasuk didalamnya dengan nama non–integer dan serta turunannya.

- -

Karena urutan iterasi merupakan implementation-dependent, pengiterasian pada array mungkin tidak membaca elemen pada urutan yang urut. Karena itu lebih baik menggunakan perulangan {{jsxref("Statements/for", "for")}} dengan menggunakan nomor indek (atau {{jsxref("Array.prototype.forEach()")}} atau {{jsxref("Statements/for...of", "for...of")}} loop) ketika mengiterasi array dimana urutan akses sangat penting.

- -

Iterasi hanya pada properti sendiri

- -

Jika anda hanya ingin mempertimbangkan properti yang melekat pada objek itu sendri, dan bukan prototypes-nya, gunakan {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}} atau lakukan {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}} cek ({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable")}} juga dapat digunakan). Alternatifnya, jika anda tahu disana tidak ada campur tangan kode luar , anda dapat memperpanjang built-in prototypes dengan metode cek.

- -

Contoh

- -

Pada fungsi berikut menggunakan sebuah objek argumen. kemudian mengiterasi pada semua properti enumerable pada objek tersebut dan mengembalikan string dari nama properti dan nilainya.

- -
var obj = {a:1, b:2, c:3};
-
-for (var prop in obj) {
-  console.log("obj." + prop + " = " + obj[prop]);
-}
-
-// Output:
-// "obj.a = 1"
-// "obj.b = 2"
-// "obj.c = 3"
- -

Fungsi berikut mengiterasi menggunakan {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}: properti turunannya tidak akan di tampilkan.

- -
var triangle = {a:1, b:2, c:3};
-
-function ColoredTriangle() {
-  this.color = "red";
-}
-
-ColoredTriangle.prototype = triangle;
-
-var obj = new ColoredTriangle();
-
-for (var prop in obj) {
-  if( obj.hasOwnProperty( prop ) ) {
-    console.log("obj." + prop + " = " + obj[prop]);
-  }
-}
-
-// Output:
-// "obj.color = red"
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}{{Spec2('ES1')}}Initial definition.
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Kompabilitas: Ekspresi Initializer

- -

Pada SpiderMonkey 40 {{geckoRelease(40)}} atau sebelumnya, bisa menggunakan ekspersi initializer (i=0) pada perulangan for...in :

- -
var obj = {a:1, b:2, c:3};
-for(var i=0 in obj) {
-  console.log(obj[i]);
-}
-// 1
-// 2
-// 3
-
- -

Perilaku non-standard ini sekarang diabaikan pada versi 40 dan selanjutnya akan disajikan dengan {{jsxref("SyntaxError")}} ("for-in loop head declarations may not have initializers") Peringatan pada konsole ({{bug(748550)}} dan {{bug(1164741)}}).

- -

Pada mesin lain seperti v8 (Chrome), Chakra (IE/Edge), dan JSC (WebKit/Safari) juga telah menyelidiki untuk menghapus perilaku non standar tersebut.

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/statements/function/index.html b/files/id/web/javascript/reference/statements/function/index.html deleted file mode 100644 index bd6b665d2e..0000000000 --- a/files/id/web/javascript/reference/statements/function/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: Deklarasi Fungsi -slug: Web/JavaScript/Reference/Statements/function -tags: - - JavaScript - - Pernyataan - - Statement -translation_of: Web/JavaScript/Reference/Statements/function -original_slug: Web/JavaScript/Reference/Statements/fungsi ---- -
{{jsSidebar("Statements")}}
- -

Deklarasi fungsi mendefinisikan sebuah fungsi dengan parameter-parameter yang ditentukan.

- -

Fungsi juga dapat didefinisikan menggukanan konstruktor {{jsxref("Function")}} dan {{jsxref("Operators/function", "function expression")}}.

- -

Sintak

- -
function name([param,[, param,[..., param]]]) {
-   [statements]
-}
-
- -
-
name
-
Nama dari fungsi.
-
- -
-
param
-
Nama dari argumen yang akan dilewatkan kepada fungsi. Jumlah maksimal dari argumen berbeda-beda di setiap mesin.
-
- -
-
statements
-
Statemen-statemen yang membentuk tubuh dari sebuah fungsi.
-
- -

Deskripsi

- -

Sebuah fungsi yang diciptakan dengan deklarasi fungsi adalah sebuah objek Function dan memiliki semua properti, method-method dan tingkah laku dari objek Function. Lihat {{jsxref("Function")}} untuk informasi mendetail tentang fungsi-fungsi.

- -

Sebuah fungsi juga dapat diciptakan menggunakan sebuah ekspresi (lihat  {{jsxref("Operators/function", "function expression")}}).

- -

Secara default, fungsi mengembalikan nilai undefined. Untuk mengembalikan nilai lain, fungsi tersebut harus memiliki sebuah {{jsxref("Statements/return", "return")}} statement yang menentukan nilai untuk dikembalikan.

- -

Fungsi yang dibuat secara kondisional

- -

Fungsi dapat dideklarasikan secara kondisional, yaitu sebuah statement fungsi dapat disarangkan di dalam sebuah statement if. Kebanyakan aplikasi perambah selain Mozilla akan memperlakukan deklarasi kondisional seperti itu sebagai sebuah deklarasi non kondisional dan menciptakan fungsi tersebut meskipun kondisi bernilai benar atau salah, lihat artikel berikut untuk ikhtisar. Untuk alasan tersebut, deklarasi kondisional seharusnya tidak digunakan -- untuk pembuatakan kondisional gunakan ekspresi fungsi sebagai gantinya.

- -

Pengangkatan deklarasi fungsi

- -

Deklarasi fungsi di javaScript mengangkat definisi fungsi. Kamu dapat menggunakan fungsi sebelum kamu mendeklarasikan fungsi tersebut.

- -
hoisted(); // logs "foo"
-
-function hoisted() {
-  console.log('foo');
-}
-
- -

Dicatat bahwa {{jsxref("Operators/function", "function expressions")}} tidak terangkat:

- -
notHoisted(); // TypeError: notHoisted is not a function
-
-var notHoisted = function() {
-   console.log('bar');
-};
-
- -

Contoh

- -

Menggunakan fungsi

- -

Kode berikut mendeklarasikan sebuah fungsi yang mengembalikan jumlah total penjualan ketika diberikan angka dari unit-unit yang terjual dari produk a, b, dan c.

- -
function calc_sales(units_a, units_b, units_c) {
-   return units_a * 79 + units_b * 129 + units_c * 699;
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-13', 'Function definition')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Kompabilitas Perambah

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Allowed in sloppy mode{{CompatChrome(49.0)}}{{CompatUnknown}}    
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Allowed in sloppy mode{{CompatNo}} -

{{CompatChrome(49.0)}}

-
{{CompatUnknown}}     -

{{CompatChrome(49.0)}}

-
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/index.html b/files/id/web/javascript/reference/statements/index.html deleted file mode 100644 index 08840f4e1a..0000000000 --- a/files/id/web/javascript/reference/statements/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: Statements -slug: Web/JavaScript/Reference/Statements -tags: - - JavaScript - - Referensi - - Statement -translation_of: Web/JavaScript/Reference/Statements ---- -
{{jsSidebar("Statements")}}
- -

Aplikasi JavaScript terdiri dari statemen dengan sebuah sintaks tertentu. Sebuah statement dapat terdiri lebih dari satu baris. Setiap statement dapat berupa sebaris kode jika di pisahkan dengan semikolon ( ; ). Bukan merupakan keyword, tapi sekumpulan keyword.

- -

Statemen dan deklarasi berdasarkan kategori

- -

Untuk daftar berdasarkan alfabet lihat pada sidebar sebelah kiri.

- -

Control flow

- -
-
{{jsxref("Statements/block", "Block")}}
-
Sebuah block statemen digunakan untuk mengelompokkan zero ( 0 ) atau lebih statement. Block ini dibatasi menggunakan kurung kurawal.
-
{{jsxref("Statements/break", "break")}}
-
Membatasi  loop, switch, atau label statement dan transfer kontrol program pada statement berdasakan statemen akhir.
-
{{jsxref("Statements/continue", "continue")}}
-
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
-
{{jsxref("Statements/Empty", "Empty")}}
-
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
-
{{jsxref("Statements/if...else", "if...else")}}
-
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
-
{{jsxref("Statements/switch", "switch")}}
-
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
-
{{jsxref("Statements/throw", "throw")}}
-
Throws a user-defined exception.
-
{{jsxref("Statements/try...catch", "try...catch")}}
-
Marks a block of statements to try, and specifies a response, should an exception be thrown.
-
- -

Deklarasi

- -
-
{{jsxref("Statements/var", "var")}}
-
Mendeklarasikan variabel, biasanya menginisialisasi ke sebuah nilai.
-
{{jsxref("Statements/let", "let")}}
-
Declares a block scope local variable, optionally initializing it to a value.
-
{{jsxref("Statements/const", "const")}}
-
Declares a read-only named constant.
-
- -

Fungsi dan class

- -
-
{{jsxref("Statements/function", "function")}}
-
Declares a function with the specified parameters.
-
{{jsxref("Statements/function*", "function*")}}
-
Generators functions enable writing iterators more easily.
-
{{jsxref("Statements/return", "return")}}
-
Specifies the value to be returned by a function.
-
{{jsxref("Statements/class", "class")}}
-
Declares a class.
-
- -

Iterations

- -
-
{{jsxref("Statements/do...while", "do...while")}}
-
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
-
{{jsxref("Statements/for", "for")}}
-
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
-
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
-
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
-
{{jsxref("Statements/for...in", "for...in")}}
-
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
-
{{jsxref("Statements/for...of", "for...of")}}
-
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
-
{{jsxref("Statements/while", "while")}}
-
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
-
- -

Others

- -
-
{{jsxref("Statements/debugger", "debugger")}}
-
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
-
{{jsxref("Statements/export", "export")}}
-
Used to export functions to make them available for imports in external modules, another scripts.
-
{{jsxref("Statements/import", "import")}}
-
Used to import functions exported from an external module, another script.
-
{{jsxref("Statements/label", "label")}}
-
Provides a statement with an identifier that you can refer to using a break or continue statement.
-
- -
-
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
-
Extends the scope chain for a statement.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
- -

See also

- - diff --git a/files/id/web/mathml/element/index.html b/files/id/web/mathml/element/index.html deleted file mode 100644 index cb570e4974..0000000000 --- a/files/id/web/mathml/element/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: MathML element reference -slug: Web/MathML/Element -tags: - - MathML - - Referensi MathML -translation_of: Web/MathML/Element ---- -

{{MathMLRef}}

- -

Ini adalah daftar alfabet dari elemen presentasi MathML.

- -

Istilah Markup presentasi digunakan untuk menggambarkan struktur tata letak notasi matematika sedangkan konten markup memberikan makna matematika yang mendasari dan tidak seharusnya diberikan oleh parser MathML (lihat {{bug (276028)}}). Jika Anda ingin mempelajari lebih lanjut tentang markup konten yang harus Anda pertimbangkan Chapter 4 pada MathML 3 specification.

- -

MathML presentation elements A  to Z

- -
-

math

- -
    -
  • {{MathMLElement("math")}} (Top-level element)
  • -
- -

A

- -
    -
  • {{MathMLElement("maction")}} (Binded actions to sub-expressions)
  • -
  • {{MathMLElement("maligngroup")}} (Alignment group)
  • -
  • {{MathMLElement("malignmark")}} (Alignment points)
  • -
- -

E

- -
    -
  • {{MathMLElement("menclose")}} (Enclosed contents)
  • -
  • {{MathMLElement("merror")}} (Enclosed syntax error messages)
  • -
- -

F

- -
    -
  • {{MathMLElement("mfenced")}} (Parentheses)
  • -
  • {{MathMLElement("mfrac")}} (Fraction)
  • -
- -

G

- -
    -
  • {{MathMLElement("mglyph")}} (Displaying non-standard symbols)
  • -
- -

I

- -
    -
  • {{MathMLElement("mi")}} (Identifier)
  • -
- -

L

- -
    -
  • {{MathMLElement("mlabeledtr")}} (Labeled row in a table or a matrix)
  • -
  • {{MathMLElement("mlongdiv")}} (Long division notation)
  • -
- -

M

- -
    -
  • {{MathMLElement("mmultiscripts")}} (Prescripts and tensor indices)
  • -
- -

N

- -
    -
  • {{MathMLElement("mn")}} (Number)
  • -
- -

O

- -
    -
  • {{MathMLElement("mo")}} (Operator)
  • -
  • {{MathMLElement("mover")}} (Overscript)
  • -
- -

P

- -
    -
  • {{MathMLElement("mpadded")}} (Space around content)
  • -
  • {{MathMLElement("mphantom")}} (Invisible content with reserved space)
  • -
- -

R

- -
    -
  • {{MathMLElement("mroot")}} (Radical with specified index)
  • -
  • {{MathMLElement("mrow")}} (Grouped sub-expressions)
  • -
- -

S

- -
    -
  • {{MathMLElement("ms")}} (String literal)
  • -
  • {{MathMLElement("mscarries")}} (Annotations such as carries)
  • -
  • {{MathMLElement("mscarry")}} (Single carry, child element of {{MathMLElement("mscarries")}})
  • -
  • {{MathMLElement("msgroup")}} (Grouped rows of {{MathMLElement("mstack")}} and {{MathMLElement("mlongdiv")}} elements)
  • -
  • {{MathMLElement("msline")}} (Horizontal lines inside {{MathMLElement("mstack")}} elements)
  • -
  • {{MathMLElement("mspace")}} (Space)
  • -
  • {{MathMLElement("msqrt")}} (Square root without an index)
  • -
  • {{MathMLElement("msrow")}} (Rows in {{MathMLElement("mstack")}} elements)
  • -
  • {{MathMLElement("mstack")}} (Stacked alignment)
  • -
  • {{MathMLElement("mstyle")}} (Style change)
  • -
  • {{MathMLElement("msub")}} (Subscript)
  • -
  • {{MathMLElement("msup")}} (Superscript)
  • -
  • {{MathMLElement("msubsup")}} (Subscript-superscript pair)
  • -
- -

T

- -
    -
  • {{MathMLElement("mtable")}} (Table or matrix)
  • -
  • {{MathMLElement("mtd")}} (Cell in a table or a matrix)
  • -
  • {{MathMLElement("mtext")}} (Text)
  • -
  • {{MathMLElement("mtr")}} (Row in a table or a matrix)
  • -
- -

U

- -
    -
  • {{MathMLElement("munder")}} (Underscript)
  • -
  • {{MathMLElement("munderover")}} (Underscript-overscript pair)
  • -
- -

Other elements

- -
    -
  • {{MathMLElement("semantics")}} (Container for semantic annotations)
  • -
  • <annotation> (Data annotations)
  • -
  • <annotation-xml> (XML annotations)
  • -
-
- -

Elemen presentasi MathML berdasarkan kategori

- -

 

- -

Elemen tingkat atas

- - - -

Elemen Token

- - - -

Tata letak umum

- - - -

Script dan batas elemen

- - - -

Tabular Matematika

- - - -

Matematika dasar

- - - -

Elemen yang tidak terkategorikan

- - - -

Anotasi semantik

- - - -

Lihat juga

- - diff --git a/files/id/web/mathml/index.html b/files/id/web/mathml/index.html deleted file mode 100644 index 7c41b63f49..0000000000 --- a/files/id/web/mathml/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: MathML -slug: Web/MathML -tags: - - Landing - - MathML - - NeedsTranslation - - Reference - - TopicStub - - Web - - XML -translation_of: Web/MathML ---- -
{{MathMLRef}}
- -

Mathematical Markup Language (MathML) is a dialect of XML for describing mathematical notation and capturing both its structure and content.

- -

Here you'll find links to documentation, examples, and tools to help you work with this powerful technology. For a quick overview, see the slides for the innovation fairs at Mozilla Summit 2013.

- -
-
-

MathML reference

- -
-
MathML element reference
-
Details about each MathML element and compatibility information for desktop and mobile browsers.
-
MathML attribute reference
-
Information about MathML attributes that modify the appearance or behavior of elements.
-
MathML examples
-
MathML samples and examples to help you understand how it works.
-
Authoring MathML
-
Suggestions and tips for writing MathML, including suggested MathML editors and how to integrate their output into Web content.
-
- -

View All...

-
- -
-

Getting help from the community

- - - -

Tools

- - - - - - -
-
- -

Browser compatibility

- - - -

{{Compat("mathml.elements.math", 0)}}

diff --git a/files/id/web/reference/api/index.html b/files/id/web/reference/api/index.html deleted file mode 100644 index d8589d167f..0000000000 --- a/files/id/web/reference/api/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Referensi Web API -slug: Web/Reference/API -tags: - - API - - Landing - - Reference - - Web - - Web Desain -translation_of: Web/Reference/API ---- -

Web menyediakan banyak API untuk melaksanakan berbagai tugas. Seluruh API ini dapat diakses menggunakan kode Javascript, dan memungkinkan kita untuk melakukan perubahan-perubahan minor kepada {{domxref("window")}} atau {{domxref("element")}} maupun menghasilkan efek-efek video dan audio yang luar biasa menggunakan API seperti WebGL dan Web Audio.

- -

Masing-masing antarmuka dari seluruh API yang ada didaftarkan pada index.

- -

Ada juga daftar dari semua event yang tersedia pada referensi event.

- -
-
-
-
Dokumen Object Model
-
DOM adalah API yang memungkinkan modifikasi pada dokumen. Memungkinkan manipulasi dari dokumen {{domxref("Node")}} dan {{domxref("Element")}}. HTML, XML, dan SVG mempunyai kelebihan itu untuk memanipulasi beberapa spesifik element.
-
Device API
-
Merupakan seperangkat APIs yang memungkinkan kita untuk mengakses ke seluruh fitur hardware yang tersedia ke halaman Web dan aplikasi. Misal. Ambient Light Sensor API, Battery Status API, Geolocation API, Pointer Lock API, Proximity API, Device Orientation API, Screen Orientation API, Vibration API.
-
Communication APIs
-
API ini memungkinkan halaman Web dan aplikasi berkomunikasi dengan halaman lain atau perangkat tertentu. Misal. Network Information API, Web Notifications, Simple Push API.
-
Data management APIs
-
Data pengguna dapat disimpan dan di kendalikan menggunakan perangkat API ini. Misal. FileHandle API, IndexedDB.
-
- -

Tambahan dari API ini yang tersedia untuk setiap halaman Web dan aplikasi, sebuah set yang lebih powerfull yaitu Mozilla API tersedia untuk aplikasi khusus dan bersertifikat.

- -
-
Privileged APIs
-
Aplikasi khusus merupakan aplikasi yang di install dengan hak khusus yang ditentukan pengguna. Privileged API meliputi: TCP Socket API, Contacts API, Device Storage API, Browser API, Camera API.
-
Certified APIs
-
Aplikasi bersertifikat merupakan aplikasi tingkat rendah yang melakukan operasi penting dalam sebuah sistem operasi seperti Firefox OS. Aplikasi Khusus tidak berinteraksi dengan aplikasi inimenggunakan Web Activities.  Certified APIs meliputi: Bluetooth API, Mobile Connection API, Network Stats API, Telephony, WebSMS, WiFi Information API, Power Management API, Settings API, Idle API, Permissions API, Time/Clock API.
-
-
- -
-

Komunitas

- -

Bergabung dengan komunitas API Web pada milis kami atau newsgroup:

- - - -

Juga, pastikan bergabung pada diskusi secara langsung di channel #webapi di IRC.

- - - -

Mungkin anda juga tertarik dengan topik berikut:

- - -
-
- -

 

diff --git a/files/id/web/reference/index.html b/files/id/web/reference/index.html deleted file mode 100644 index 445d9adf8a..0000000000 --- a/files/id/web/reference/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Web technology reference -slug: Web/Reference -tags: - - Landing - - NeedsTranslation - - Reference - - TopicStub - - Web -translation_of: Web/Reference ---- -

{{draft()}}

-

The open Web is built using a number of technologies. Below you'll find links to our reference material for each of them.

-
-
-

Core Web technologies

-
-
- Web API interface reference
-
- Reference material for each of the interfaces that comprise the Web's APIs, including the DOM and all of the related APIs and interfaces you can use to build Web content and apps. This list covers all interfaces, arranged alphabetically.
-
- Web APIs
-
- A list of the individual APIs and technology suites that make up the overall Web API.
-
- HTML
-
- HyperText Markup Language is the language used to describe and define the content of a Web page.
-
- CSS
-
- Cascading Style Sheets are used to describe the appearance of Web content.
-
- SVG
-
- Scalable Vector Graphics let you describe images as sets of vectors and shapes in order to allow them to scale smoothly regardless of the size at which they're drawn.
-
- MathML
-
- The Mathematical Markup Language makes it possible to display complex mathematical equations and syntax.
-
-
-
-

Other technologies

-

To be completed soon...

-
-
-

 

diff --git a/files/id/web/security/index.html b/files/id/web/security/index.html deleted file mode 100644 index cc8b113b7a..0000000000 --- a/files/id/web/security/index.html +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Web security -slug: Web/Security -translation_of: Web/Security ---- -

-Memastikan bahwa situs web Anda atau aplikasi web terbuka aman sangat penting. Bahkan bug sederhana dalam kode Anda dapat menyebabkan kebocoran informasi pribadi, dan orang jahat di luar sana berusaha mencari cara untuk mencuri data. Artikel berorientasi keamanan web yang tercantum di sini menyediakan informasi yang dapat membantu Anda mengamankan situs Anda dan kode dari serangan dan pencurian data

- - -

{{LandingPageListSubpages}}

- -

{{QuickLinksWithSubpages}}

diff --git a/files/id/web/web_components/index.html b/files/id/web/web_components/index.html deleted file mode 100644 index 326823bdbb..0000000000 --- a/files/id/web/web_components/index.html +++ /dev/null @@ -1,230 +0,0 @@ ---- -title: Web Components -slug: Web/Web_Components -tags: - - Artikel Web - - Gambaran - - HTML Imports - - JavaScript - - Landing - - Pengembangan Web - - Template - - Web Components - - component - - custom elements - - shadow dom - - slot -translation_of: Web/Web_Components ---- -
{{DefaultAPISidebar("Web Components")}}
- -
-

Web Components adalah kumpulan fitur teknologi yang memungkinkan Anda membuat elemen khusus yang dapat digunakan kembali dengan fungsionalitasnya yang dikemas jauh dari sisa kode Anda dan menggunakannya di aplikasi web Anda.

-
- -

Konsep dan penggunaan

- -

Sebagai pengembang, kita semua tahu bahwa menggunakan kembali kode sebanyak mungkin merupakan ide yang bagus. Hal ini biasanya tidak mudah untuk struktur markup kustom memikirkan HTML kompleks (serta gaya dan skrip terkait) yang terkadang harus Anda tulis untuk memnuat kontrol UI khusus, dan bagaimana menggunakannya beberapa kali dapat mengubah halaman Anda menjadi berantankan jika Anda tidak berhati-hati.

- -

Web Components bertujun untuk menyelesaikan masalah yang terdiri dari tiga teknologi utama, yang dapat digunakan bersama untuk membuat elemen kustom serbaguna dengan fungsionalitas terenkapsulasi yang dapat digunakan kembali di mana pun Anda suka tanpa takut benturan kode.

- - - -

Pendekatan dasar untuk mengimplementasikan web component biasanya terlihat seperti ini:

- -
    -
  1. Buat kelas di mana Anda menentukan fungsionalitas web component Anda, menggunakan sintaks kelas ECMAScript 2015 (lihat Kelas untuk informasi lebih lanjut).
  2. -
  3. Daftarkan elemen kustom baru Anda menggunakan metode {{domxref ("CustomElementRegistry.define ()")}}, meneruskan nama elemen yang akan ditentukan, kelas atau fungsi di mana fungsionalitasnya ditentukan, dan secara opsional, elemen apa yang diwarisi dari.
  4. -
  5. Jika perlu, lampirkan shadow DOM ke elemen khusus menggunakan metode {{domxref ("Element.attachShadow ()")}}. Tambahkan child element, event listener, dll., Ke shadow DOM menggunakan metode DOM biasa.
  6. -
  7. Jika perlu, tentukan template HTML menggunakan {{htmlelement ("template")}} dan {{htmlelement ("slot")}}. Sekali lagi gunakan metode DOM biasa untuk mengkloning template dan melampirkannya ke shadow DOM Anda.
  8. -
  9. Gunakan elemen kustom Anda di mana pun Anda suka di halaman Anda, seperti yang Anda lakukan pada elemen HTML biasa.
  10. -
- -

Tutorial

- -
-
Menggunakan custom element
-
Panduan yang menunjukkan cara menggunakan fitur elemen khusus untuk membuat komponen web sederhana, serta melihat callback siklus proses dan beberapa fitur lanjutan lainnya.
-
Menggunakan shadow DOM
-
Panduan yang mempelajari dasar-dasar shadow DOM, menunjukkan cara melampirkan shadow DOM ke elemen, menambahkan ke shadow DOM tree, menatanya, dan banyak lagi.
-
Menggunakan templates and slots
-
Panduan yang menunjukkan cara menentukan struktur HTML yang dapat digunakan kembali menggunakan elemen {{htmlelement ("template")}} dan {{htmlelement ("slot")}}, lalu menggunakan struktur tersebut di dalam komponen web Anda.
-
- -

Referensi

- -

Custom elements

- -
-
{{domxref("CustomElementRegistry")}}
-
Berisi fungsionalitas yang terkait dengan elemen kustom, terutama metode {{domxref ("CustomElementRegistry.define()")}} yang digunakan untuk mendaftarkan elemen kustom baru sehingga dapat digunakan di dokumen Anda.
-
{{domxref("Window.customElements")}}
-
Mengembalikan referensi ke objek {{domxref("CustomElementRegistry.define()")}}.
-
Life cycle callbacks
-
Fungsi panggilan balik khusus yang ditentukan di dalam definisi kelas elemen khusus, yang memengaruhi perilakunya: -
    -
  • connectedCallback: Dipanggil saat elemen khusus pertama kali dihubungkan ke DOM dokumen.
  • -
  • disconnectedCallback: Dipanggil ketika elemen khusus terputus dari DOM dokumen.
  • -
  • adoptedCallback: Dipanggil ketika elemen kustom dipindahkan ke dokumen baru.
  • -
  • attributeChangedCallback: Dipanggil ketika salah satu atribut elemen khusus ditambahkan, dihapus, atau diubah.
  • -
-
-
-
    -
-
-
- -
-
Ekstensi untuk membuat elemen bawaan khusus
-
-
    -
  • Atribut HTML global {{htmlattrxref ("is")}}: Memungkinkan Anda menentukan bahwa elemen HTML standar harus berperilaku seperti elemen bawaan khusus terdaftar.
  • -
  • Opsi "is" dari metode {{domxref ("Document.createElement()")}}: Memungkinkan Anda membuat instance elemen HTML standar yang berperilaku seperti elemen bawaan khusus terdaftar yang diberikan.
  • -
-
-
CSS pseudo-classes
-
Pseudo-classes yang berkaitan secara khusus dengan elemen khusus: -
    -
  • {{cssxref(":defined")}}: Mencocokkan elemen apa pun yang ditentukan, termasuk elemen bawaan dan elemen khusus yang ditentukan dengan CustomElementRegistry.define()).
  • -
  • {{cssxref(":host")}}: Memilih shadow host dari shadow DOM yang berisi CSS yang digunakan di dalamnya.
  • -
  • {{cssxref(":host()")}}: Memilih shadow host dari shadow DOM yang berisi CSS yang digunakan di dalamnya (sehingga Anda dapat memilih elemen khusus dari dalam shadow DOM-nya) tetapi hanya jika pemilih yang diberikan sebagai parameter fungsi cocok dengan shadow host.
  • -
  • {{cssxref(":host-context()")}}: Memilih shadow host dari shadow DOM yang berisi CSS yang digunakan di dalamnya (sehingga Anda dapat memilih elemen khusus dari dalam shadow DOM-nya) tetapi hanya jika pemilih yang diberikan sebagai parameter fungsi cocok dengan leluhur host bayangan di tempat itu itu berada di dalam hierarki DOM.
  • -
-
-
Pseudo-elements yang berkaitan secara khusus dengan elemen khusus: -
    -
  • {{cssxref("::part")}}: Merepresentasikan elemen apa pun dalam shadow tree yang memiliki atribut {{HTMLAttrxRef ("part")}} yang cocok.
  • -
-
-
- -

Shadow DOM

- -
-
{{domxref("ShadowRoot")}}
-
Merepresentasikan root node dari shadow DOM subtree.
-
{{domxref("DocumentOrShadowRoot")}}
-
Fitur penentu mixin yang tersedia di seluruh dokumen dan shadow roots.
-
Ekstensi {{domxref("Element")}}
-
Ekstensi ke antarmuka Element yang terkait dengan shadow DOM: -
    -
  • Metode {{domxref ("Element.attachShadow ()")}} melampirkan shadow DOM tree ke elemen yang ditentukan.
  • -
  • Properti {{domxref ("Element.shadowRoot")}} mengembalikan shadow root yang dilampirkan ke elemen yang ditentukan, atau null jika tidak ada shadow root yang terpasang.
  • -
-
-
Penambahan {{domxref ("Node")}} yang relevan
-
Penambahan antarmuka Node yang relevan dengan shadow DOM: -
    -
  • Metode {{domxref ("Node.getRootNode ()")}} mengembalikan root objek konteks, yang secara opsional menyertakan shadow root jika tersedia.
  • -
  • Properti {{domxref ("Node.isConnected")}} mengembalikan boolean yang menunjukkan apakah Node terhubung (langsung atau tidak langsung) ke objek konteks atau tidak, misalnya objek {{domxref ("Document")}} dalam kasus DOM normal, atau {{domxref ("ShadowRoot")}} untuk shadow DOM.
  • -
-
-
Ekstensi {{domxref("Event")}}
-
Ekstensi ke antarmuka Event yang terkait dengan shadow DOM: -
    -
  • {{domxref ("Event.composed")}}: Mengembalikan {{jsxref ("Boolean")}} yang menunjukkan apakah acara akan menyebar melintasi batas shadow DOM ke DOM standar (true), atau tidak (false).
  • -
  • {{domxref("Event.composedPath")}}: Mengembalikan event's path (objek tempat pemroses akan dipanggil). Ini tidak termasuk node dalam shadow tree jika shadow root dibuat dengan {{domxref ("ShadowRoot.mode")}} ditutup.
  • -
-
-
- -

HTML templates

- -
-
{{htmlelement("template")}}
-
Berisi fragmen HTML yang tidak dirender saat dokumen penampung awalnya dimuat, tetapi dapat ditampilkan saat runtime menggunakan JavaScript, terutama digunakan sebagai dasar struktur elemen khusus. Antarmuka DOM terkait adalah {{domxref ("HTMLTemplateElement")}}.
-
{{htmlelement("slot")}}
-
Placeholder di dalam web component yang dapat Anda isi dengan markup Anda sendiri, yang memungkinkan Anda membuat DOM tree terpisah dan menyajikannya bersama-sama. Antarmuka DOM terkait adalah {{domxref ("HTMLSlotElement")}}
-
Atribut HTML global slot
-
Menetapkan slot di shadow tree shadow DOM ke sebuah elemen.
-
{{domxref("Slotable")}}
-
Mixin yang diimplementasikan oleh node {{domxref ("Element")}} dan {{domxref ("Text")}}, mendefinisikan fitur yang memungkinkan mereka menjadi konten elemen {{htmlelement ("slot")}}. Mixin mendefinisikan satu atribut, {{domxref ("Slotable.assignedSlot")}}, yang mengembalikan referensi ke slot tempat node disisipkan.
-
- -
-
Ekstensi {{domxref("Element")}}
-
Extensions ke antarmuka Element yang terkait dengan slot: -
    -
  • {{domxref("Element.slot")}}: Mengembalikan nama slot shadow DOM yang dilampirkan ke elemen.
  • -
-
-
CSS pseudo-elements
-
Pseudo-elements yang berkaitan secara khusus dengan slot: -
    -
  • {{cssxref("::slotted")}}: Mencocokkan konten apa pun yang dimasukkan ke dalam slot.
  • -
-
-
Event {{event("slotchange")}}
-
Diaktifkan pada instance {{domxref ("HTMLSlotElement")}} (elemen {{htmlelement ("slot")}}) saat node yang ada di slot itu berubah.
-
- -

Contoh

- -

Kami sedang membangun sejumlah contoh dalam repo GitHub contoh komponen web kami. Lebih banyak akan ditambahkan seiring berjalannya waktu.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName("HTML WHATWG","scripting.html#the-template-element","<template> element")}}{{Spec2("HTML WHATWG")}}Definisi dari {{HTMLElement("template")}}.
{{SpecName("HTML WHATWG","custom-elements.html#custom-elements","custom elements")}}{{Spec2("HTML WHATWG")}}Definisi dari HTML Custom Elements.
{{SpecName("DOM WHATWG","#shadow-trees","shadow trees")}}{{Spec2("DOM WHATWG")}}Definisi dari Shadow DOM.
{{SpecName("HTML Imports", "", "")}}{{Spec2("HTML Imports")}}Definisi Impor HTML awal.
{{SpecName("Shadow DOM", "", "")}}{{Spec2("Shadow DOM")}}Definisi Shadow DOM awal.
- -

Kompabilitas browser

- -

Umumnya:

- - - -

Untuk dukungan browser mendetail dari fitur tertentu, Anda harus membaca halaman referensi yang tercantum di atas.

- -

Lihat juga

- - -- cgit v1.2.3-54-g00ecf