From 6ef1fa4618e08426b874529619a66adbd3d1fcf0 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 12:07:59 +0100 Subject: unslug ja: move --- files/ja/web/javascript/getting_started/index.html | 303 --------------- .../index.html | 25 -- .../guide/core_language_features/index.html | 10 - .../guide/creating_a_regular_expression/index.html | 31 -- .../defining_getters_and_setters/index.html | 89 ----- .../defining_methods/index.html | 39 -- .../index.html | 13 - .../deleting_properties/index.html | 20 - .../guide/creating_new_objects/index.html | 17 - .../indexing_object_properties/index.html | 9 - .../using_a_constructor_function/index.html | 57 --- .../using_object_initializers/index.html | 23 -- .../using_this_for_object_references/index.html | 25 -- .../ja/web/javascript/guide/expressions/index.html | 16 - .../loop_statements/break_statement/index.html | 24 -- .../loop_statements/continue_statement/index.html | 46 --- .../do...while_statement/index.html | 19 - .../guide/loop_statements/for_statement/index.html | 50 --- .../javascript/guide/loop_statements/index.html | 17 - .../loop_statements/label_statement/index.html | 19 - .../loop_statements/while_statement/index.html | 35 -- .../object_manipulation_statements/index.html | 51 --- .../guide/objects_and_properties/index.html | 32 -- .../web/javascript/guide/obsolete_pages/index.html | 10 - .../function_object/index.html | 44 --- .../operators/arithmetic_operators/index.html | 47 --- .../operators/assignment_operators/index.html | 61 --- .../operators/comparison_operators/index.html | 67 ---- .../guide/operators/logical_operators/index.html | 63 ---- .../guide/operators/special_operators/index.html | 197 ---------- .../guide/operators/string_operators/index.html | 8 - .../escape_and_unescape_functions/index.html | 14 - .../predefined_functions/eval_function/index.html | 12 - .../guide/predefined_functions/index.html | 17 - .../creating_the_hierarchy/index.html | 134 ------- .../guide/the_employee_example/index.html | 31 -- .../object_properties/adding_properties/index.html | 19 - .../object_properties/index.html | 13 - .../inheriting_properties/index.html | 24 -- .../guide/using_the_arguments_object/index.html | 36 -- files/ja/web/javascript/guide/variables/index.html | 62 ---- .../index.html | 193 ---------- .../index.html | 381 ------------------- .../index.html | 411 --------------------- .../global_objects/array/index/index.html | 22 -- .../global_objects/array/input/index.html | 25 -- .../global_objects/array/prototype/index.html | 176 --------- .../asyncfunction/prototype/index.html | 109 ------ .../global_objects/atomics/notify/index.html | 142 +++++++ .../global_objects/atomics/wake/index.html | 142 ------- .../finalizationregistry/cleanupsome/index.html | 74 ---- .../intl/datetimeformat/prototype/index.html | 88 ----- .../webassembly/instance/prototype/index.html | 64 ---- .../webassembly/memory/prototype/index.html | 71 ---- .../webassembly/table/prototype/index.html | 75 ---- .../operators/comparison_operators/index.html | 232 ------------ .../operators/logical_operators/index.html | 295 --------------- .../reference/operators/special/index.html | 5 - .../operators/special_operators/index.html | 5 - .../javascript/reference/reserved_words/index.html | 89 ----- .../reference/statements/yield/index.html | 7 - 61 files changed, 142 insertions(+), 4293 deletions(-) delete mode 100644 files/ja/web/javascript/getting_started/index.html delete mode 100644 files/ja/web/javascript/guide/class-based_vs._prototype-based_languages/index.html delete mode 100644 files/ja/web/javascript/guide/core_language_features/index.html delete mode 100644 files/ja/web/javascript/guide/creating_a_regular_expression/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/defining_getters_and_setters/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/defining_methods/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/defining_properties_for_an_object_type/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/deleting_properties/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/indexing_object_properties/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/using_a_constructor_function/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/using_object_initializers/index.html delete mode 100644 files/ja/web/javascript/guide/creating_new_objects/using_this_for_object_references/index.html delete mode 100644 files/ja/web/javascript/guide/expressions/index.html delete mode 100644 files/ja/web/javascript/guide/loop_statements/break_statement/index.html delete mode 100644 files/ja/web/javascript/guide/loop_statements/continue_statement/index.html delete mode 100644 files/ja/web/javascript/guide/loop_statements/do...while_statement/index.html delete mode 100644 files/ja/web/javascript/guide/loop_statements/for_statement/index.html delete mode 100644 files/ja/web/javascript/guide/loop_statements/index.html delete mode 100644 files/ja/web/javascript/guide/loop_statements/label_statement/index.html delete mode 100644 files/ja/web/javascript/guide/loop_statements/while_statement/index.html delete mode 100644 files/ja/web/javascript/guide/object_manipulation_statements/index.html delete mode 100644 files/ja/web/javascript/guide/objects_and_properties/index.html delete mode 100644 files/ja/web/javascript/guide/obsolete_pages/index.html delete mode 100644 files/ja/web/javascript/guide/obsolete_pages/predefined_core_objects/function_object/index.html delete mode 100644 files/ja/web/javascript/guide/operators/arithmetic_operators/index.html delete mode 100644 files/ja/web/javascript/guide/operators/assignment_operators/index.html delete mode 100644 files/ja/web/javascript/guide/operators/comparison_operators/index.html delete mode 100644 files/ja/web/javascript/guide/operators/logical_operators/index.html delete mode 100644 files/ja/web/javascript/guide/operators/special_operators/index.html delete mode 100644 files/ja/web/javascript/guide/operators/string_operators/index.html delete mode 100644 files/ja/web/javascript/guide/predefined_functions/escape_and_unescape_functions/index.html delete mode 100644 files/ja/web/javascript/guide/predefined_functions/eval_function/index.html delete mode 100644 files/ja/web/javascript/guide/predefined_functions/index.html delete mode 100644 files/ja/web/javascript/guide/the_employee_example/creating_the_hierarchy/index.html delete mode 100644 files/ja/web/javascript/guide/the_employee_example/index.html delete mode 100644 files/ja/web/javascript/guide/the_employee_example/object_properties/adding_properties/index.html delete mode 100644 files/ja/web/javascript/guide/the_employee_example/object_properties/index.html delete mode 100644 files/ja/web/javascript/guide/the_employee_example/object_properties/inheriting_properties/index.html delete mode 100644 files/ja/web/javascript/guide/using_the_arguments_object/index.html delete mode 100644 files/ja/web/javascript/guide/variables/index.html delete mode 100644 files/ja/web/javascript/guide/writing_a_regular_expression_pattern/index.html delete mode 100644 files/ja/web/javascript/introduction_to_object-oriented_javascript/index.html delete mode 100644 files/ja/web/javascript/introduction_to_using_xpath_in_javascript/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/array/index/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/array/input/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/array/prototype/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/asyncfunction/prototype/index.html create mode 100644 files/ja/web/javascript/reference/global_objects/atomics/notify/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/atomics/wake/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/finalizationregistry/cleanupsome/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/webassembly/instance/prototype/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/webassembly/memory/prototype/index.html delete mode 100644 files/ja/web/javascript/reference/global_objects/webassembly/table/prototype/index.html delete mode 100644 files/ja/web/javascript/reference/operators/comparison_operators/index.html delete mode 100644 files/ja/web/javascript/reference/operators/logical_operators/index.html delete mode 100644 files/ja/web/javascript/reference/operators/special/index.html delete mode 100644 files/ja/web/javascript/reference/operators/special_operators/index.html delete mode 100644 files/ja/web/javascript/reference/reserved_words/index.html delete mode 100644 files/ja/web/javascript/reference/statements/yield/index.html (limited to 'files/ja/web/javascript') diff --git a/files/ja/web/javascript/getting_started/index.html b/files/ja/web/javascript/getting_started/index.html deleted file mode 100644 index b87febbe05..0000000000 --- a/files/ja/web/javascript/getting_started/index.html +++ /dev/null @@ -1,303 +0,0 @@ ---- -title: Getting Started (Javascript Tutorial) -slug: Web/JavaScript/Getting_Started -translation_of: Learn/Getting_started_with_the_web/JavaScript_basics -translation_of_original: Web/JavaScript/Getting_Started ---- -

Why JavaScript?

-

JavaScript is a powerful, complicated, and often misunderstood computer language. It enables the rapid development of applications in which users can enter data and view results easily.

-

The primary advantage to JavaScript, which is also known as ECMAScript, centers around the Web browser, thus having the ability to produce the same results on all platforms supported by the browser. The examples on this page, just like Google Maps, run on Linux, Windows, and Mac OS. With the recent growth of numerous JavaScript libraries it is now easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. Unlike the hype around other technologies pushed by various proprietary interests, JavaScript is really the only cross-platform, client-side programming language that is both free and universally adopted.

-

What you should already know

-

JavaScript is a very easy language to start programming with. All you need is a text editor and a Web browser to get started.

-

There are many other technologies that can be integrated into and developed along with JavaScript that are beyond the scope of this document. Don't expect to make a whole application like Google Maps all on your first day!

-

Getting started

-

Getting started with JavaScript is very easy. You don't have to have complicated development programs installed. You don't have to know how to use a shell, program Make, or use a compiler. JavaScript is interpreted by your Web browser. All you have to do is save your program as a text file and then open it up in your Web browser. That's it!

-

JavaScript is a great programming language for introductory computer languages. It allows instant feedback to the new student and teaches them about tools they will likely find useful in their real life. This is in stark contrast to C, C++, and Java which are really only useful for dedicated software developers.

-

Browser compatibility issues

-

There are variations between what functionality is available in the different browsers. Mozilla, Microsoft IE, Apple Safari, and Opera fluctuate in behavior. We intend on documenting these variations. You can mitigate these issues by using the various cross-platform JavaScript APIs that are available. These APIs provide common functionality and hide these browser fluctuations from you.

-

How to try the examples

-

The examples below have some sample code. There are many ways to try these examples out. If you already have your own website, then you should be able to just save these examples as new Web pages on your website.

-

If you do not have your own website, you can save these examples as files on your computer and open them up with the Web browser you are using now. JavaScript is a very easy language to use for beginning programmers for this reason. You don't need a compiler or a development environment; you and your browser are all you need to get started!

-

Example: Catching a mouse click

-

The specifics of event handling (event types, handler registration, propagation, etc.) are too extensive to be fully covered in this simple example. However, this example cannot demonstrate catching a mouse click without delving a little into the JavaScript event system. Just keep in mind that this example will only graze the full details about JavaScript events and that if you wish to go beyond the basic capabilities described here, read more about the JavaScript event system.

-

'Mouse' events are a subset of the total events issued by a Web browser in response to user actions. The following is a list of the events emitted in response to a user's mouse action:

- -

Note that in the latest versions of HTML, the inline event handlers, i.e. the ones added as tag attributes, are expected to be all lowercase and that event handlers in script are always all lowercase.

-

The simplest method for capturing these events, to register event handlers - using HTML - is to specify the individual events as attributes for your element. Example:

-
  <span onclick="alert('Hello World!');">Click Here</span>
-

The JavaScript code you wish to execute can be inlined as the attribute value or you can call a function which has been defined in a <script> block within the HTML page:

-
<script type="text/javascript">
-  function clickHandler () {
-     alert ("Hello, World!");
-  }
-</script>
-<span onclick="clickHandler();">Click Here</span>
-

Additionally, the event object which is issued can be captured and referenced, providing the developer with access to specifics about the event such as which object received the event, the event's type, and which mouse button was clicked. Using the inline example again:

-
<script type="text/javascript">
-  function clickHandler(event) {
-    var eType = event.type;
-    /* the following is for compatibility */
-    /* Moz populates the target property of the event object */
-    /* IE populates the srcElement property */
-    var eTarget = event.target || event.srcElement;
-
-    alert( "Captured Event (type=" + eType + ", target=" + eTarget );
-  }
-</script>
-<span onclick="clickHandler(event);">Click Here</span>
-

In addition to registering to receive events in your HTML, you can likewise set the same attributes of any HTMLElement objects generated by your JavaScript. The example below instantiates a span object, appends it to the page body, and registers the span object to receive mouse-over, mouse-out, mouse-down, and mouse-up events.

-
<body></body>
-<script type="text/javascript">
-  function mouseeventHandler(event) {
-    /* The following is for compatibility */
-    /* IE does NOT by default pass the event object */
-    /* obtain a ref to the event if one was not given */
-    if (!event) event = window.event;
-
-    /* obtain event type and target as earlier */
-    var eType = event.type;
-    var eTarget = event.target || event.srcElement;
-    alert(eType +' event on element with id: '+ eTarget.id);
-  }
-
- function onloadHandler () {
-   /* obtain a ref to the 'body' element of the page */
-   var body = document.body;
-   /* create a span element to be clicked */
-   var span = document.createElement('span');
-   span.id = 'ExampleSpan';
-   span.appendChild(document.createTextNode ('Click Here!'));
-
-   /* register the span object to receive specific mouse events -
-      notice the lowercase of the events but the free choice in the names of the handlers you replace them with.
-   */
-   span.onmousedown = mouseeventHandler;
-   span.onmouseup = mouseeventHandler;
-   span.onmouseover = mouseeventHandler;
-   span.onmouseout = mouseeventHandler;
-
-   /* display the span on the page */
-   body.appendChild(span);
-}
-
-window.onload = onloadHandler; // since we replace the handler, we do NOT have () after the function name
-</script>
-

Example: Catching a keyboard event

-

Similar to the "Catching a mouse event" example above, catching a keyboard event relies on exploring the JavaScript event system. Keyboard events are fired whenever any key is used on the keyboard.

-

The list of available keyboard events emitted in response to a keyboard action is considerably smaller than those available for mouse:

- -

In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g., 'a'), charCode is set to the code of that character, respecting the letter case (i.e., charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode.

-

The simplest method for capturing keyboard events is again to register event handlers within the HTML, specifying the individual events as attributes for your element. Example:

-
  <input type="text" onkeypress="alert ('Hello World!');" />
-
-

As with mouse events, the JavaScript code you wish to execute can be inlined as the attribute value or you can call a function which has been defined in a <script> block within the HTML page:

-
<script type="text/javascript">
-  function keypressHandler() {
-    alert ("Hello, World!");
-  }
-</script>
-
-<input onkeypress="keypressHandler();" />
-
-

Capturing the event and referencing the target (i.e., the actual key that was pressed) is achieved in a similar way to mouse events:

-
<script type="text/javascript">
-  function keypressHandler(evt) {
-      var eType = evt.type; // Will return "keypress" as the event type
-      /* here we again need to use a cross browser method
-         mozilla based browsers return which and others keyCode.
-         The Conditional operator or ternary is a good choice */
-      var keyCode = evt.which?evt.which:evt.keyCode;
-      var eCode = 'keyCode is ' + keyCode;
-      var eChar = 'charCode is ' + String.fromCharCode(keyCode); // or evt.charCode
-      alert ("Captured Event (type=" + eType + ", key Unicode value=" + eCode + ", ASCII value=" + eChar + ")");
-   }
-</script>
-<input onkeypress="keypressHandler(event);" />
-

Capturing any key event from the page can be done by registering the event at the document level and handling it in a function:

-
<script type="text/javascript">
-  document.onkeypress = keypressHandler(event);
-  document.onkeydown = keypressHandle(event);
-  document.onkeyup =keypressHandle(event)
-
-</script>
-

Here is a complete example that shows key event handling:

-
<!DOCTYPE html>
-<html>
-<head>
-  <script>
-    var metaChar = false;
-    var exampleKey = 16;
-    function keyEvent(event) {
-      var key = event.keyCode || event.which; // alternative to ternary - if there is no keyCode, use which
-      var keychar = String.fromCharCode(key);
-      if (key==exampleKey) { metaChar = true; }
-      if (key!=exampleKey) {
-         if (metaChar) {
-            alert("Combination of metaKey + " + keychar)
-            metaChar = false;
-         } else { alert("Key pressed " + key); }
-      }
-    }
-    function metaKeyUp (event) {
-      var key = event.keyCode || event.which;
-      if (key==exampleKey) { metaChar = false; }
-    }
-  </script>
-</head>
-<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)">
-    Try pressing any key!
-</body>
-</html>
-

Browser bugs and quirks

-

The two properties made available through the key events are keyCode and charCode. In simple terms, keyCode refers to the actual keyboard key that was pressed by the user, while charCode is intended to return that key's ASCII value. These two values may not necessarily be the same; for instance, a lower case 'a' and an upper case 'A' have the same keyCode, because the user presses the same key, but a different charCode because the resulting character is different.

-

The way in which browsers interpret the charCode is not a consistently-applied process. For example, Internet Explorer and Opera do not support charCode. However, they give the character information in keyCode, but only onkeypress. Onkeydown and onkeyup keyCode contain key information. Firefox uses a different word, "which", to distinguish the character.

-

Refer to the Mozilla Documentation on Keyboard Events for a further treatment of keyboard events.

-

{{ draft() }}

-

Example: Dragging images around

-

The following example allows moving the image of Firefox around the page:

-
<!DOCTYPE html>
-<html>
-<head>
-<style type='text/css'>
-img { position: absolute; }
-</style>
-
-<script type='text/javascript'>
-window.onload = function() {
-
-  movMeId = document.getElementById("ImgMov");
-  movMeId.style.top = "80px";
-  movMeId.style.left = "80px";
-
-  document.onmousedown = coordinates;
-  document.onmouseup = mouseup;
-
-  function coordinates(e) {
-    if (e == null) { e = window.event;}
-
-    // e.srcElement holds the target element in IE, whereas e.target holds the target element in Firefox
-    // Both properties return the HTML element the event took place on.
-
-    var sender = (typeof( window.event ) != "undefined" ) ? e.srcElement : e.target;
-
-    if (sender.id=="ImgMov") {
-      mouseover = true;
-      pleft = parseInt(movMeId.style.left);
-      ptop = parseInt(movMeId.style.top);
-      xcoor = e.clientX;
-      ycoor = e.clientY;
-      document.onmousemove = moveImage;
-      return false;
-    } else {
-        return false;
-    }
-  }
-
-  function moveImage(e) {
-    if (e == null) { e = window.event; }
-    movMeId.style.left = pleft+e.clientX-xcoor+"px";
-    movMeId.style.top = ptop+e.clientY-ycoor+"px";
-    return false;
-  }
-
-  function mouseup(e) {
-    document.onmousemove = null;
-  }
-}
-</script>
-</head>
-
-<body>
-  <img id="ImgMov" src="http://placehold.it/100x100&text=JS" width="64" height="64" />
-  <p>Drag and drop around the image in this page.</p>
-</body>
-
-</html>
-

Example: Resizing things

-
- Example of resizing an image (the actual image is not resized, only the image's rendering.) -
  <!DOCTYPE html>
-  <html>
-    <head>
-      <style>
-        #resizeImage {
-          margin-left: 100px;
-        }
-      </style>
-      <script>
-      window.onload = function() {
-
-        var resizeId = document.getElementById("resizeImage");
-        var resizeStartCoordsX,
-            resizeStartCoordsY,
-            resizeEndCoordsX,
-            resizeEndCoordsY;
-
-        var resizeEndCoords;
-        var resizing = false;
-
-        document.onmousedown = coordinatesMousedown;
-        document.onmouseup = coordinatesMouseup;
-
-        function coordinatesMousedown(e) {
-          if (e == null) {
-            e = window.event;
-          }
-
-          var element = (typeof( window.event ) != 'undefined' ) ? e.srcElement : e.target;
-
-          if (element.id == "resizeImage") {
-            resizing = true;
-            resizeStartCoordsX = e.clientX;
-            resizeStartCoordsY = e.clientY;
-          }
-          return false;
-        }
-
-        function coordinatesMouseup(e) {
-          if (e == null) {
-            e = window.event;
-          }
-
-          if (resizing === true) {
-            var currentImageWidth = parseInt(resizeId.width);
-            var currentImageHeight = parseInt(resizeId.height);
-
-            resizeEndCoordsX = e.clientX;
-            resizeEndCoordsY = e.clientY;
-
-            resizeId.style.height = currentImageHeight - (resizeStartCoordsY - resizeEndCoordsY) + 'px';
-            resizeId.style.width = currentImageWidth - (resizeStartCoordsX - resizeEndCoordsX) + 'px';
-
-            resizing = false;
-          }
-          return false;
-        }
-      }
-      </script>
-    </head>
-
-    <body>
-      <img id="resizeImage" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png"
-width="64" height="64" />
-      <p>Click on the image and drag for resizing.</p>
-    </body>
-
-  </html>
-
-

Example: Drawing Lines

-

{{todo("Need Content. Or, remove headline")}}

diff --git a/files/ja/web/javascript/guide/class-based_vs._prototype-based_languages/index.html b/files/ja/web/javascript/guide/class-based_vs._prototype-based_languages/index.html deleted file mode 100644 index 800f222ea4..0000000000 --- a/files/ja/web/javascript/guide/class-based_vs._prototype-based_languages/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Class-Based vs. Prototype-Based Languages -slug: Web/JavaScript/Guide/Class-Based_vs._Prototype-Based_Languages ---- -

クラスベース言語とプロトタイプベース言語

-

Java や C++ といったクラスベースのオブジェクト指向言語はクラスとインスタンスという 2 つの異なる実体があるという概念に基づいています。

- -

JavaScript のようなプロトタイプベース言語はこの区別がありません。単にオブジェクトがあるだけです。プロトタイプベース言語には原型的なオブジェクトという概念があります。このオブジェクトは新しいオブジェクトの初期プロパティを取得する元になるテンプレートとして使用されます。どのオブジェクトもそれ独自のプロパティを指定できます。オブジェクト作成時にも実行時にも可能です。さらに、どのオブジェクトも別のオブジェクトに対するプロトタイプとして関連付けることができます。2 つ目のオブジェクトが 1 つ目のオブジェクトのプロトタイプを共有するということもできます。

-

クラスの定義

-

クラスベース言語ではクラス定義ごとにクラスを定義します。定義では特殊なメソッドを指定してそのクラスのインスタンスを作成することができます。そのようなメソッドはコンストラクタと呼びます。コンストラクタメソッドはインスタンスのプロパティに対する初期値を指定することができます。また、作成時に他の適当な処理を実行することもできます。new 演算子をコンストラクタメソッドと一緒に用いることでクラスのインスタンスを作成できます。

-

JavaScript は同様のモデルに従っていますが、コンストラクタと別になっているクラス定義がありません。その代わりに、プロパティと値からなる特定の初期的なセットを持つオブジェクトを作成するコンストラクタ関数を定義します。どの JavaScript 関数もコンストラクタとして使用できます。new 演算子をコンストラクタ関数とともに使用することで新しいオブジェクトを作成します。

-

サブクラスと継承

-

クラスベース言語ではクラス定義を通じてクラスの階層を作ります。クラス定義では新しいクラスがある既存のクラスのサブクラスになるように指定することができます。サブクラスはスーパークラスの全プロパティを継承します。さらに新しくプロパティを追加したり継承したものを変更することもできます。例えば、Employee クラスが name および dept プロパティのみを含んでおり、Manager は reports プロパティを追加する Employee のサブクラスであるとします。この場合、Manager クラスのインスタンスは name、dept、reports という 3 つのプロパティをすべて持つことになります。

-

JavaScript では、原型的なオブジェクトをどのコンストラクタ関数にも結びつけることができるようにして継承を実装しています。そのため、全く同じような Employee と Manager の例を作成することができますが、使用する用語が若干異なります。まず、Employee コンストラクタ関数を定義します。これは name および dept プロパティを指定します。次に Manager コンストラクタ関数を定義します。これは reports プロパティを指定します。最後に新しい Employee オブジェクトを Manager コンストラクタ関数に対するプロトタイプとして代入します。そして新しい Manager を作成すると、このオブジェクトは Employee オブジェクトから name および dept プロパティを継承します。

-

プロパティの追加と削除

-

クラスベース言語では一般的にクラスをコンパイル時に生成し、コンパイル時または実行時にクラスのインスタンスを作成します。クラス定義後にそのクラスのプロパティの数や型を変更することはできません。しかし、JavaScript ではどんなオブジェクトでも実行時にプロパティを追加したり削除したりすることができます。あるオブジェクトのセットでプロトタイプとして使用されているオブジェクトにプロパティを追加すると、そのプロトタイプの使用元であるオブジェクトにも新しいプロパティが追加されます。

-

違いの概要

-

次の表でこれらの違いをいくつか短くまとめてみます。この章の残りで、JavaScript のコンストラクタとプロトタイプを用いてオブジェクト階層を作成することについての詳細を説明していきます。また、この方法が Java ではどう変わるかという比較もします。

- -
クラスベース (Java) プロトタイプベース (JavaScript)
クラスとインスタンスは異なる実体である。 すべてのオブジェクトはインスタンスである。
クラス定義を用いてクラスを定義する。また、コンストラクタメソッドを用いてクラスをインスタンス化する。 コンストラクタ関数を用いてオブジェクトのセットを定義し、作成する。
new 演算子を用いて単一のオブジェクトを作成する。 同じ。
既存のクラスのサブクラスを定義するクラス定義を用いてオブジェクト階層を構築する。 コンストラクタ関数に結びつけられたプロトタイプとしてオブジェクトを代入することでオブジェクト階層を構築する。
クラスチェーンに従ってプロパティを継承する。 プロトタイプチェーンに従ってプロパティを継承する。
クラス定義がクラスの全インスタンスの全プロパティを指定する。実行時に動的にプロパティを追加することはできない。 コンストラクタ関数またはプロトタイプがプロパティの初期セットを指定する。個々のオブジェクトやオブジェクトの全体のセットに動的にプロパティを追加したり、それらからプロパティを除去したりできる。
-
-

{{ PreviousNext("Core_JavaScript_1.5_Guide:Predefined_Core_Objects:String_Object", "Core_JavaScript_1.5_Guide:The_Employee_Example") }}

-
-

{{ languages( { "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/以類別為基礎的語言_vs._以原型為基礎的語言", "en": "en/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages", "es": "es/Gu\u00eda_JavaScript_1.5/Lenguajes_basados_en_clases_frente_a_basados_en_prototipos", "fr": "fr/Guide_JavaScript_1.5/Langages_bas\u00e9s_sur_les_classes_et_langages_bas\u00e9s_sur_les_prototypes", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/J\u0119zyki_oparte_na_klasach_vs._oparte_na_prototypach", "zh-cn": "cn/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages" } ) }}

diff --git a/files/ja/web/javascript/guide/core_language_features/index.html b/files/ja/web/javascript/guide/core_language_features/index.html deleted file mode 100644 index 2161ec589e..0000000000 --- a/files/ja/web/javascript/guide/core_language_features/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Core Language Features -slug: Web/JavaScript/Guide/Core_Language_Features ---- -
-{{page("/ja/docs/Core_JavaScript_1.5_Guide/Values()")}} -{{page("/ja/docs/Core_JavaScript_1.5_Guide/Variables()")}} -{{page("/ja/docs/Core_JavaScript_1.5_Guide/Constants()")}} -{{page("/ja/docs/Core_JavaScript_1.5_Guide/Literals()")}} -{{page("/ja/docs/Core_JavaScript_1.5_Guide/Unicode()")}}
diff --git a/files/ja/web/javascript/guide/creating_a_regular_expression/index.html b/files/ja/web/javascript/guide/creating_a_regular_expression/index.html deleted file mode 100644 index 19935b8b55..0000000000 --- a/files/ja/web/javascript/guide/creating_a_regular_expression/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: 正規表現の作成 -slug: Web/JavaScript/Guide/Creating_a_Regular_Expression ---- -

正規表現の作成

-

正規表現は 2 つの方法で作ることができます。

- -
var re = /ab+c/; 
-
-
-
-
- 正規表現リテラルでは、スクリプトが評価されるときにその正規表現をコンパイルします。正規表現を定数として残しておくときは、この方法を使用するとよりよいパフォーマンスが得られます。
-
-
-
- -
var re = new RegExp("ab+c"); 
-
-
-
-
- コンストラクタ関数を使用すると、実行時にその正規表現をコンパイルします。正規表現パターンが変わることがわかっている場合や、パターンがわからない場合、ユーザが入力するなど、別のソースからパターンを取得する場合はコンストラクタ関数を使用してください。
-
-
-
-

{{ PreviousNext("JavaScript/Guide/Operators/Special_Operators", "JavaScript/Guide/Writing_a_Regular_Expression_Pattern") }}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/defining_getters_and_setters/index.html b/files/ja/web/javascript/guide/creating_new_objects/defining_getters_and_setters/index.html deleted file mode 100644 index 8ee9381575..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/defining_getters_and_setters/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: ゲッターとセッターの定義 -slug: Web/JavaScript/Guide/Creating_New_Objects/Defining_Getters_and_Setters ---- -

ゲッターとセッターの定義

- -

ゲッターはある属性の値を取得するメソッドです。セッターは属性に値を設定するメソッドです。全ての定義済みコアオブジェクトと、新しいプロパティの追加をサポートしているユーザ定義オブジェクトに対してゲッターとセッターを定義できます。ゲッターとセッターの定義にはオブジェクトリテラル構文を使用します。

- -

以下の例では、ユーザ定義オブジェクト o についてゲッターとセッターがどのように機能するかを説明します。JavaScript シェル とは JavaScript コードをバッチモードで、またはインタラクティブにテストすることができる、開発者向けのアプリケーションのことです。

- -

o オブジェクトのプロパティは以下のとおりです。

- - - -
js> o = new Object;
-[object Object]
-js> o = {a:7, get b() {return this.a+1; }, set c(x) {this.a = x/2}};
-[object Object]
-js> o.a
-7
-js> o.b
-8
-js> o.c = 50
-js> o.a
-25
-js>
-
- -

次の例では、 Date プロトタイプを拡張して定義済み Date クラスの全インスタンスに year プロパティを追加する様子を表しています。Date クラスの既存の getFullYear および setFullYear メソッドを使用して year プロパティのゲッターとセッターを実装します。

- -

これらの文は year プロパティに対するゲッターとセッターを定義しています。

- -
js> var d = Date.prototype;
-js> d.__defineGetter__("year", function() { return this.getFullYear(); });
-js> d.__defineSetter__("year", function(y) { this.setFullYear(y); });
-
- -

これらの文は Date オブジェクトで定義したゲッターとセッターを使用しています。

- -
js> var now = new Date;
-js> print(now.year);
-2000
-js> now.year=2001;
-987617605170
-js> print(now);
-Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
-
- -
JavaScript 1.5 の開発期間中に getter =setter = といった式を使用して新しいゲッターやセッターを既存のオブジェクトで定義するようになっていた時期がありました。この構文は現在は廃止予定であり、現行の JS 1.5 エンジンでは警告を発します。また、将来的には構文エラーになります。使用を避けるようにしてください
- -

 

- -

概要

- -

原則的にゲッターとセッターは次のどちらかに属します。

- - - -

オブジェクト初期化子 を用いてゲッターやセッターを定義する際には、ゲッターメソッドの先頭に get を、セッターメソッドの先頭に set をそれぞれ付けなくてはなりません。セッターメソッドはセットする新しい値を受けわたすための引数を 1 つだけ持ちます。ゲッターメソッドはパラメータを受け取るようにしてはいけません。

- -
o = {
-  a:7,
-  get b() { return this.a+1; },
-  set c(x) { this.a = x/2; }
-};
-
- -

ゲッターもセッターも、__defineGetter__ および __defineSetter__ という 2 つの特別なメソッドを用いて、オブジェクト作成後でも、そのオブジェクトに追加することができます。両メソッドの第 1 引数にはそのゲッターやセッターの名前を文字列で指定します。第 2 引数にはゲッターやセッターとして呼び出す関数を指定します。前の例を別の方法で実装したものを以下に示します。

- -
o.__defineGetter__("b", function() { return this.a+1; });
-o.__defineSetter__("c", function(x) { this.a = x/2; });
-
- -

2 つの形式のうちどちらを選択するかはあなたのプログラミングスタイルや、目の前の課題次第によります。プロトタイプの定義時にオブジェクト初期化子を使用しているのであれば、最初の形式を選択するのがよいでしょう。この形式はよりコンパクトかつ自然です。ゲッターやセッターを後から追加する必要がある場合は、プロトタイプや特定のオブジェクトを書いていないため、第 2 の形式しか使用できません。第 2 の形式は JavaScript の動的性質をおそらく最もよく表していますが、コードが可読性が下がったり、理解しづらいものとなることがあります。

- -
-

Firefox 3.0 より前のバージョンではゲッターとセッターが DOM 要素に対してサポートされていません。古いバージョンの Firefox では例外を投げることなく失敗します。そのときに例外が必要であれば、HTMLElement のプロトタイプを変更し (HTMLElement.prototype.__define{{ mediawiki.external('SG') }}etter__)、例外を投げるようにして回避してください。

- -

Firefox 3.0 では、定義済みのプロパティでゲッターとセッターを定義すると例外が投げられます。そのプロパティは事前に削除しておく必要があります。これは古いバージョンの Firefox には当てはまりません。

-
- -

{{ PreviousNext("JavaScript/Guide/Creating_New_Objects/Using_this_for_Object_References", "JavaScript/Guide/Creating_New_Objects/Deleting_Properties") }}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/defining_methods/index.html b/files/ja/web/javascript/guide/creating_new_objects/defining_methods/index.html deleted file mode 100644 index 74731a99d1..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/defining_methods/index.html +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: メソッドの定義 -slug: Web/JavaScript/Guide/Creating_New_Objects/Defining_Methods ---- -

メソッドの定義

-

メソッドとはあるオブジェクトに結びつけられた関数のことです。メソッドは、通常の関数の定義と同じ方法で定義します。既存のオブジェクトに関数を結びつけるには次の構文を使用します。

-
object.methodname = function_name
-
-

ここで、object は既存のオブジェクトを、methodname はメソッドに割り当てる名前を、function_name は関数の名前をそれぞれ表しています。

-

すると、次のようにしてオブジェクトのコンテキストでそのメソッドを呼び出すことができます。

-
object.methodname(params);
-
-

オブジェクトのコンストラクタ関数にメソッドの定義を含めることで、あるオブジェクトの種類についてのメソッドを定義することができます。例えば、以前に定義した car オブジェクトのプロパティを整形して表示する関数を定義します。

-
function displayCar() {
-   var result = "A Beautiful " + this.year + " " + this.make
-      + " " + this.model;
-   pretty_print(result);
-}
-
-

pretty_print は水平方向の罫線と文字列を表示する関数です。this を使用してそのメソッドを抱えているオブジェクトを参照しています。

-

次の文

-
this.displayCar = displayCar;
-
-

をオブジェクトの定義に加えることで、この関数を car のメソッドにすることができます。そうすると、car の完全な定義は次のようになります。

-
function car(make, model, year, owner) {
-   this.make = make;
-   this.model = model;
-   this.year = year;
-   this.owner = owner;
-   this.displayCar = displayCar;
-}
-
-

すると、次のようにして各オブジェクトについて displayCar メソッドを呼び出すことができます。

-
car1.displayCar()
-car2.displayCar()
-
-

こうすると次の図のような出力が得られます。

-

Image:obja.gif 図 7.1:メソッドの出力の表示

-

{{ PreviousNext("JavaScript/Guide/Creating_New_Objects/Defining_Properties_for_an_Object_Type", "JavaScript/Guide/Creating_New_Objects/Using_this_for_Object_References") }}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/defining_properties_for_an_object_type/index.html b/files/ja/web/javascript/guide/creating_new_objects/defining_properties_for_an_object_type/index.html deleted file mode 100644 index b5136b203e..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/defining_properties_for_an_object_type/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Defining Properties for an Object Type -slug: >- - Web/JavaScript/Guide/Creating_New_Objects/Defining_Properties_for_an_Object_Type ---- -

あるオブジェクトの種類に対するプロパティの定義

-

prototype プロパティを用いて、定義済みのオブジェクトの種類にプロパティを追加することができます。この方法では、指定した種類のすべてのオブジェクトで共有されるプロパティを定義することになります。そのオブジェクトのあるインスタンス 1 つだけということではありません。次のコードは color プロパティを car という種類の全オブジェクトに追加し、値をオブジェクト car1color プロパティに代入します。

-
car.prototype.color=null;
-car1.color="black";
-
-

詳しくは コア JavaScript リファレンス 内の Function オブジェクトの prototype プロパティ を参照してください。

- -

{{ PreviousNext("JavaScript/Guide/Creating_New_Objects/Indexing_Object_Properties", "JavaScript/Guide/Creating_New_Objects/Defining_Methods") }}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/deleting_properties/index.html b/files/ja/web/javascript/guide/creating_new_objects/deleting_properties/index.html deleted file mode 100644 index 749ee722f5..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/deleting_properties/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: プロパティの削除 -slug: Web/JavaScript/Guide/Creating_New_Objects/Deleting_Properties ---- -

プロパティの削除

-

delete 演算子を用いることでプロパティを除去することができます。次のコードでプロパティの除去方法を示します。

-
// 新しいオブジェクト myobj を作成。2 つのプロパティ、a および b を持つ。
-myobj = new Object;
-myobj.a = 5;
-myobj.b = 12;
-
-// a プロパティを除去。myobj には b プロパティだけが残っている。
-delete myobj.a;
-
-

delete を使用することでグローバル変数を削除することもできます。ただし、これは var キーワードを使用せずにその変数を宣言した場合のみです。

-
g = 17;
-delete g;
-
-

さらなる情報については delete をご覧ください。

-

{{PreviousNext("JavaScript/Guide/Creating_New_Objects/Defining_Getters_and_Setters", "JavaScript/Guide/Predefined_Core_Objects")}}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/index.html b/files/ja/web/javascript/guide/creating_new_objects/index.html deleted file mode 100644 index 0cbbc1753c..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 新しいオブジェクトの作成 -slug: Web/JavaScript/Guide/Creating_New_Objects ---- -

新しいオブジェクトの作成

-

JavaScript には多くの定義済みオブジェクトがあります。さらに、自分でオブジェクトを作り出すことができます。JavaScript 1.2 以降では、オブジェクト初期化子を用いてオブジェクトを作成できます。もう 1 つの方法として、まずコンストラクタ関数を作成し、それからその関数と new 演算子を用いてオブジェクトのインスタンスを作成することもできます。

- -

{{ PreviousNext("JavaScript/Guide/Objects_and_Properties", "JavaScript/Guide/Creating_New_Objects/Using_Object_Initializers") }}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/indexing_object_properties/index.html b/files/ja/web/javascript/guide/creating_new_objects/indexing_object_properties/index.html deleted file mode 100644 index 024de85654..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/indexing_object_properties/index.html +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: オブジェクトのプロパティに対するインデックス付け -slug: Web/JavaScript/Guide/Creating_New_Objects/Indexing_Object_Properties ---- -

オブジェクトのプロパティのインデックス付け

-

JavaScript 1.0 では、オブジェクトのプロパティを、そのプロパティ名や順序のインデックスで参照できます。しかしながら、JavaScript 1.1 以降では、最初にプロパティをその名前で定義すると、常にその名前で参照しなければならず、また、最初にプロパティをインデックスで定義すると、常にそのインデックスで参照しなければなりません。

-

先の Car というオブジェクトの種類の例のようにコンストラクタ関数を用いてオブジェクトとそのプロパティを作成したとき、また、それぞれのプロパティを明示的に定義したとき(例:myCar.color = "red")に、これは適用されます。そのため、myCar{{ mediawiki.external(5) }} = "25 mpg" のように、最初にインデックスを用いてオブジェクトのプロパティを定義した場合、myCar{{ mediawiki.external(5) }} のようにそのプロパティを後から参照できるようになります。

-

このルールの例外は、forms 配列のように HTML から反映されたオブジェクトです。これらの配列内のオブジェクトは、その順番を表す数(文書内のどこにあるかに基づく)か、またはその名前(定義されている場合)のどちらかで常に参照できます。例えば、文書内の 2 番目の <FORM> タグが "myForm" という NAME 属性を持っている場合、document.forms{{ mediawiki.external(1) }}document.forms{{ mediawiki.external('\"myForm\"') }}document.myForm とすることでそのフォームを参照できます。

-

{{ PreviousNext("JavaScript/Guide/Creating_New_Objects/Using_a_Constructor_Function", "JavaScript/Guide/Creating_New_Objects/Defining_Properties_for_an_Object_Type") }}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/using_a_constructor_function/index.html b/files/ja/web/javascript/guide/creating_new_objects/using_a_constructor_function/index.html deleted file mode 100644 index f3abc30e89..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/using_a_constructor_function/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: コンストラクタ関数の使用 -slug: Web/JavaScript/Guide/Creating_New_Objects/Using_a_Constructor_Function ---- -

コンストラクタ関数の使用

-

もう 1 つの方法として、次の 2 つのステップでオブジェクトを作成することができます。

-
    -
  1. コンストラクタ関数を書くことでオブジェクトの種類を定義する。
  2. -
  3. new を用いてそのオブジェクトのインスタンスを作成する。
  4. -
-

オブジェクトの種類を定義するために、その名前、プロパティ、メソッドを定義する関数を作成する必要があります。例えば、車についてのオブジェクトの種類を作成したいとします。そしてこの種類のオブジェクトに car という名前を付け、make、model、および year というプロパティを持たせたいとします。こうするためには次のような関数を書きます。

-
function car(make, model, year) {
-   this.make = make;
-   this.model = model;
-   this.year = year;
-}
-
-

関数に渡された値に基づいてオブジェクトのプロパティに値を代入するために this を使用しています。

-

すると、次のようにして mycar というオブジェクトを作成することができるようになります。

-
mycar = new car("Eagle", "Talon TSi", 1993);
-
-

この文は mycar を作成し、そのプロパティ用に指定した値を代入します。その結果、mycar.make の値は "Eagle" という文字列、mycar.year は 1993 という整数というようになります。

-

new を呼び出すことで car オブジェクトをいくらでも作ることができます。

-
kenscar = new car("Nissan", "300ZX", 1992);
-vpgscar = new car("Mazda", "Miata", 1990);
-
-

それ自身別のオブジェクトであるというようなプロパティを持つオブジェクトを作ることができます。例えば、次のように person というオブジェクトを定義するとします。

-
function person(name, age, sex) {
-   this.name = name;
-   this.age = age;
-   this.sex = sex;
-}
-
-

そして、次のように 2 つの新しい person オブジェクトのインスタンスを作成します。

-
rand = new person("Rand McKinnon", 33, "M");
-ken = new person("Ken Jones", 39, "M");
-
-

次のようにして、car の定義を書き換えて、person オブジェクトをとる owner プロパティを持たせることができます。

-
function car(make, model, year, owner) {
-   this.make = make;
-   this.model = model;
-   this.year = year;
-   this.owner = owner;
-}
-
-

新しいオブジェクトのインスタンスを作成するために、次のようにします。

-
car1 = new car("Eagle", "Talon TSi", 1993, rand);
-car2 = new car("Nissan", "300ZX", 1992, ken);
-
-

新しいオブジェクトの作成時に文字列リテラルや整数値を渡す代わりに、上記の文ではオブジェクト rand および ken を所有者を表す引数として渡しています。car2 の所有者の名前を知りたい場合は次のプロパティにアクセスすることで可能になります。

-
car2.owner.name
-
-

以前に定義したオブジェクトにいつでもプロパティを追加できることに注意してください。例えば次の文

-
car1.color = "black"
-
-

はプロパティ color を car1 に追加し、それに "black" という値を代入します。しかしながら、この方法では他のどのオブジェクトにも影響を与えません。同じ種類の全オブジェクトに新しいプロパティを追加するには、そのプロパティを car というオブジェクトの種類の定義に追加する必要があります。

-

{{ PreviousNext("JavaScript/Guide/Creating_New_Objects/Using_Object_Initializers", "JavaScript/Guide/Creating_New_Objects/Indexing_Object_Properties") }}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/using_object_initializers/index.html b/files/ja/web/javascript/guide/creating_new_objects/using_object_initializers/index.html deleted file mode 100644 index 0a817b5407..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/using_object_initializers/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: オブジェクト初期化子の使用 -slug: Web/JavaScript/Guide/Creating_New_Objects/Using_Object_Initializers ---- -

オブジェクト初期化子の使用

-

コンストラクタ関数を使用してオブジェクトを作成する方法だけではなく、オブジェクト初期化子を使用してもオブジェクトを作成することができます。オブジェクト初期化子を使うことはリテラル表示を用いてオブジェクトを作成するということです。「オブジェクト初期化子」は C++ でも同じ意味で使用されている用語です。

-

オブジェクト初期化子を使用したオブジェクトの構文は次のとおりです。

-
var obj = { property_1:   value_1,   // property_# は識別子でもよい
-            2:            value_2,   // あるいは数値でもよい
-            ...,
-            "property_n": value_n }; // あるいは文字列でもよい
-
-

ここで、obj は新しいオブジェクトの名前を、各 property_i は識別子(名前、数値、文字列リテラルのいずれか)を、各 value_i はその値を property_i に代入する式をそれぞれ表しています。obj および代入部分はなくてもかまいません。このオブジェクトを別の場所で参照する必要がないのであれば変数に代入する必要はありません。(文が期待されているところにオブジェクトリテラルを置く場合、リテラルを丸括弧で囲み、ブロック文と間違われないようにする必要があるかもしれません。)

-

トップレベルのスクリプトでオブジェクト初期化子を使用してオブジェクトを作成した場合、JavaScript はオブジェクトリテラルを含む式を評価するたびにそのオブジェクトを解釈します。さらに、関数内で使用された初期化子はその関数が呼び出されるたびに作成されます。

-

次の文は、式 cond が true の場合かつその場合に限り、あるオブジェクトを作成し、それを変数 x に代入します。

-
if (cond) x = {hi:"there"};
-
-

次の例は 3 つのプロパティを持つ myHonda を作成します。engine プロパティは自らもプロパティを持つオブジェクトでもあることに注意してください。

-
myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}};
-
-

オブジェクト初期化子を使用して配列を作成することもできます。配列リテラル を参照してください。

-

JavaScript 1.1 以前ではオブジェクト初期化子を使用することはできません。コンストラクタ関数を使用するか、他のオブジェクトが備えているそのような用途の関数を使用しないとオブジェクトを作成できません。コンストラクタ関数の使用 をご覧ください。

-

{{ PreviousNext("JavaScript/Guide/Creating_New_Objects", "JavaScript/Guide/Creating_New_Objects/Using_a_Constructor_Function") }}

diff --git a/files/ja/web/javascript/guide/creating_new_objects/using_this_for_object_references/index.html b/files/ja/web/javascript/guide/creating_new_objects/using_this_for_object_references/index.html deleted file mode 100644 index 5fbd3b8aff..0000000000 --- a/files/ja/web/javascript/guide/creating_new_objects/using_this_for_object_references/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: this を用いたオブジェクト参照 -slug: Web/JavaScript/Guide/Creating_New_Objects/Using_this_for_Object_References ---- -

this を用いたオブジェクト参照

-

JavaScript にはカレントオブジェクトを参照するメソッド内で使用できる特殊なキーワード、this があります。例えば、あるオブジェクトの value プロパティの妥当性を確認する validate という関数があるとします。関数にはそのオブジェクトと、上限および下限の値を渡します。

-
function validate(obj, lowval, hival) {
-   if ((obj.value < lowval) || (obj.value > hival))
-      alert("Invalid Value!");
-}
-
-

各フォーム要素の onchange イベントハンドラにおいて validate を呼び出します。this を使うことで form 要素を渡すことができます。次の例をご覧ください。

-
<input type="text" name="age" size="3"
-   onChange="validate(this, 18, 99)">
-
-

一般に this はあるメソッド内でそのメソッドを呼び出したオブジェクトを参照します。

-

form プロパティと組み合わせることで、this はカレントオブジェクトの親のフォームを参照できます。次の例では、myForm というフォームに Text オブジェクトとボタンが格納されています。ユーザがボタンをクリックすると、Text オブジェクトの値にフォーム名がセットされます。ボタンの onclick イベントハンドラは this.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>
-
-

{{ PreviousNext("JavaScript/Guide/Creating_New_Objects/Defining_Methods", "JavaScript/Guide/Creating_New_Objects/Defining_Getters_and_Setters") }}

diff --git a/files/ja/web/javascript/guide/expressions/index.html b/files/ja/web/javascript/guide/expressions/index.html deleted file mode 100644 index 4feb2b1aa8..0000000000 --- a/files/ja/web/javascript/guide/expressions/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Expressions -slug: Web/JavaScript/Guide/Expressions ---- -
{{ 英語版章題("Expressions") }}
-

-

とは、リテラル、変数、演算子、そして単一の値に評価する式からなる有効なセットです。この値には数値、文字列、論理値が使用できます。

-

概念的に、式は 2 つの種類に分けることができます。ある値を変数に代入するものと、単純にある値を持つものです。例えば、x = 7 という式は x に 7 という値を代入する式です。この式自体の評価結果は 7 です。このような式では代入演算子を用います。一方、3 + 4 という式では単純に評価結果が 7 になります。この式は代入を行いません。このような式で用いられる演算子は単に演算子と呼ばれます。

-

JavaScript には以下の種類の式があります。

- -

{{ PreviousNext("JavaScript/Guide/Unicode", "JavaScript/Guide/Operators") }}

diff --git a/files/ja/web/javascript/guide/loop_statements/break_statement/index.html b/files/ja/web/javascript/guide/loop_statements/break_statement/index.html deleted file mode 100644 index 35cc94abdf..0000000000 --- a/files/ja/web/javascript/guide/loop_statements/break_statement/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: break 文 -slug: Web/JavaScript/Guide/Loop_Statements/break_Statement ---- -

break 文

-

break 文は loop 文や switch 文、label 文から抜け出すために使用します。

- -

break 文は次のように使用します。

-
    -
  1. break;
  2. -
  3. break label;
  4. -
-

1番目の形式の構文は最も内側のループもしくは switch から抜けます。2番目の形式の構文は指定した label 文から抜けます。

-


- 次の例は、その値が theValue である要素のインデックスが見つかるまで、配列の要素について繰り返します。

-
for (i = 0; i < a.length; i++) {
-   if (a[i] == theValue)
-      break;
-}
-
-

{{ PreviousNext("JavaScript/Guide/Loop_Statements/label_Statement", "JavaScript/Guide/Loop_Statements/continue_Statement") }}

diff --git a/files/ja/web/javascript/guide/loop_statements/continue_statement/index.html b/files/ja/web/javascript/guide/loop_statements/continue_statement/index.html deleted file mode 100644 index f7a5697eeb..0000000000 --- a/files/ja/web/javascript/guide/loop_statements/continue_statement/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: continue 文 -slug: Web/JavaScript/Guide/Loop_Statements/continue_Statement ---- -

continue 文

-

continue 文は while 文、do-while 文、for 文、label 文をリスタートさせるために用います。

- -

continue 文は次のように使用します。

-
    -
  1. continue
  2. -
  3. continue label
  4. -
-

例 1
- 次の例では、i の値が 3 のときに実行される continue 文を用いた while ループを示します。こうすることで n は順に 1、3、7、12 という値をとります。

-
i = 0;
-n = 0;
-while (i < 5) {
-   i++;
-   if (i == 3)
-      continue;
-   n += i;
-}
-
-

例 2
- checkiandj というラベルの付いた文の中に checkj というラベルの付いた文があります。continue に出くわすと、プログラムは checkj の現在の反復を終了し、次の反復を始めます。continue に出くわすたびに、条件が false になるまで checkj を繰り返します。false が返されると checkiandj 文の残りを完了し、条件が false を返すまで checkiandj を繰り返します。false が返されると checkiandj に続く文が実行されます。

-

continuecheckiandj というラベルを持っているとプログラムは checkiandj 文の最初から続けます。

-
checkiandj :
-   while (i < 4) {
-      document.write(i + "<br/>");
-      i += 1;
-      checkj :
-         while (j > 4) {
-            document.write(j + "<br/>");
-            j -= 1;
-            if ((j % 2) == 0)
-               continue checkj;
-            document.write(j + " is odd.<br/>");
-         }
-      document.write("i = " + i + "<br/>");
-      document.write("j = " + j + "<br/>");
-   }
-
-

{{ PreviousNext("JavaScript/Guide/Loop_Statements/break_Statement", "JavaScript/Guide/Object_Manipulation_Statements") }}

diff --git a/files/ja/web/javascript/guide/loop_statements/do...while_statement/index.html b/files/ja/web/javascript/guide/loop_statements/do...while_statement/index.html deleted file mode 100644 index 6e1df1e586..0000000000 --- a/files/ja/web/javascript/guide/loop_statements/do...while_statement/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: do...while 文 -slug: Web/JavaScript/Guide/Loop_Statements/do...while_Statement ---- -

do...while 文

-

do...while 文は指定した条件が false に評価されるまで繰り返します。do...while 文は次のように使用します。

-
do
-   statement
-while (condition);
-
-

statement は条件がチェックされる前に一度実行されます。複数の文を実行するにはブロック文 ({ ... }) を使用して文をグループ化してください。condition が true の場合、その文が再び実行されます。毎回実行された後に条件がチェックされます。条件が false ときは実行が停止され、コントロールが do...while の後に続く文に渡されます。

-


- 次の例では do ループは最低 1 回は反復され、i が 5 より小さくなくなるまで反復されます。

-
do {
-   i += 1;
-   document.write(i);
-} while (i < 5);
-
-

{{ PreviousNext("JavaScript/Guide/Loop_Statements/for_Statement", "JavaScript/Guide/Loop_Statements/while_Statement") }}

diff --git a/files/ja/web/javascript/guide/loop_statements/for_statement/index.html b/files/ja/web/javascript/guide/loop_statements/for_statement/index.html deleted file mode 100644 index b2dccec25b..0000000000 --- a/files/ja/web/javascript/guide/loop_statements/for_statement/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: for 文 -slug: Web/JavaScript/Guide/Loop_Statements/for_Statement ---- -

for 文

-

for ループは指定した条件が false に評価されるまで繰り返します。JavaScript の for ループは Java や C の for ループに似ています。for 文は次のように使用します。

-
for ([initialExpression]; [condition]; [incrementExpression])
-   statement
-
-

for ループを実行すると以下のことが起こります。

-
    -
  1. 初期化式 initialExpression があれば実行されます。この式は通常、1 つかそれ以上のループカウンタを初期化しますが、構文的にはある程度複雑な式も指定できます。また、この式は変数を宣言することもできます。
  2. -
  3. condition 式が評価されます。condition の値が true であればループ文が実行されます。condition が false の場合は for ループは終了します。condition 式が完全に省略されている場合、条件は true であると仮定されます。
  4. -
  5. statement が実行されます。複数の式を実行するにはブロック文 ({ ... }) を使用して文をグループ化してください。
  6. -
  7. 更新式 incrementExpression があれば実行されます。そしてコントロールがステップ 2 に戻ります。
  8. -
-


- 次の関数には、スクローリングリスト(複数選択できる Select オブジェクト)で選択されたオプションの数を数える for 文が含まれています。for 文では変数 i が宣言され、それが 0 に初期化されています。iSelect オブジェクトのオプションの個数より小さいかをチェックし、続く if 文を実行し、ループが 1 回りしたら i を 1 だけ増加させます。

-
<script type="text/javascript">//<![CDATA[
-
-function howMany(selectObject) {
-   var numberSelected = 0;
-   for (var i = 0; i < selectObject.options.length; i++) {
-      if (selectObject.options[i].selected)
-         numberSelected++;
-   }
-   return numberSelected;
-}
-
-//]]></script>
-<form name="selectForm">
-   <p>
-      <strong>Choose some music types, then click the button below:</strong>
-      <br/>
-      <select 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 type="button" value="How many are selected?"
-         onclick="alert ('Number of options selected: ' + howMany(document.selectForm.musicTypes))"/>
-   </p>
-</form>
-
-

{{ PreviousNext("JavaScript/Guide/Loop_Statements", "JavaScript/Guide/Loop_Statements/do...while_Statement") }}

diff --git a/files/ja/web/javascript/guide/loop_statements/index.html b/files/ja/web/javascript/guide/loop_statements/index.html deleted file mode 100644 index 54ef32d2c9..0000000000 --- a/files/ja/web/javascript/guide/loop_statements/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: ループ文 -slug: Web/JavaScript/Guide/Loop_Statements ---- -

ループ文

-

ループは指定した条件が満たされている限り繰り返し実行されるコマンドのセットです。JavaScript は、label はもちろん、for、do while、while といったループ文をサポートしています(label 自体はループ文ではありませんが、これらの文とともに頻繁に使用されます)。さらに、break および continue 文をループ文の中で使うことができます。

-

さらに for...in 文も文を繰り返し実行しますが、これはオブジェクトの操作に使用します。オブジェクト操作文 をご覧ください。

-

ループ文は以下のとおりです。

- -

{{ PreviousNext("JavaScript/Guide/Conditional_Statements", "JavaScript/Guide/Loop_Statements/for_Statement") }}

diff --git a/files/ja/web/javascript/guide/loop_statements/label_statement/index.html b/files/ja/web/javascript/guide/loop_statements/label_statement/index.html deleted file mode 100644 index d0b878455b..0000000000 --- a/files/ja/web/javascript/guide/loop_statements/label_statement/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: label 文 -slug: Web/JavaScript/Guide/Loop_Statements/label_Statement ---- -

label 文

-

label を使うと、そのプログラムのどこからでも参照できる、識別子を持った文を作ることができます。例えば、ラベルを使用してあるループに名前を付けると、break 文や continue 文を使用してプログラムがループを脱出するべきかそのまま実行を継続するべきかを示すことができます。

-

label 文は次のように使用します。

-
label :
-   statement
-
-

label の値は予約語でなければどんな JavaScript の識別子でも使用できます。ラベルを用いて名前を付ける statement はどんな文でも結構です。

-


- この例では markLoop というラベルを用いて while ループに名前を付けています。

-
markLoop:
-while (theMark == true)
-   doSomething();
-}
-
-

{{ PreviousNext("JavaScript/Guide/Loop_Statements/while_Statement", "JavaScript/Guide/Loop_Statements/break_Statement") }}

diff --git a/files/ja/web/javascript/guide/loop_statements/while_statement/index.html b/files/ja/web/javascript/guide/loop_statements/while_statement/index.html deleted file mode 100644 index 77fd191f75..0000000000 --- a/files/ja/web/javascript/guide/loop_statements/while_statement/index.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: while 文 -slug: Web/JavaScript/Guide/Loop_Statements/while_Statement ---- -

while 文

-

while 文は、指定した条件が true に評価される限り文を実行します。while 文は次のように使用します。

-
while (condition)
-   statement
-
-

条件が false になるとループ内の statement の実行が停止し、ループの後に続く文にコントロールが渡されます。

-

ループの statement を実行する前に条件がテストされます。条件が true を返すと statement が実行され、再び条件がテストされます。条件が false を返すと、実行が停止され、while の後に続く文にコントロールが渡されます。

-

複数の文を実行するにはブロック文 ({ ... }) を用いて文をグループ化してください。

-

例 1
- 次の while ループでは n が 3 より小さい限り反復されます。

-
n = 0;
-x = 0;
-while (n < 3) {
-   n++;
-   x += n;
-}
-
-

それぞれの反復で、ループは n をインクリメントし、その値を x に加えています。その結果、xn は次の値をとります。

- -

第 3 段階が完了すると条件 n < 3 が true ではなくなっているため、ループは終了します。

-

例 2
- 無限ループは避けてください。ループの条件が最終的には false になることを確認してください。そうしないとループが終了しなくなります。次の while ループ内の文は永久に実行されます。条件が決して false にならないためです。

-
while (true) {
-   alert("Hello, world");
-}
-
-

{{ PreviousNext("JavaScript/Guide/Loop_Statements/do...while_Statement", "JavaScript/Guide/Loop_Statements/label_Statement") }}

diff --git a/files/ja/web/javascript/guide/object_manipulation_statements/index.html b/files/ja/web/javascript/guide/object_manipulation_statements/index.html deleted file mode 100644 index ddf781e031..0000000000 --- a/files/ja/web/javascript/guide/object_manipulation_statements/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Object Manipulation Statements -slug: Web/JavaScript/Guide/Object_Manipulation_Statements ---- -

オブジェクト操作文

-

JavaScript はオブジェクトの操作に for...infor each...in および with 文を使用します。

-

for...in 文

-

for...in 文は指定した変数をオブジェクトの全プロパティに対して反復します。それぞれのプロパティに対して JavaScript は指定した文を実行します。for...in 文は次のように使用します。

-
for (variable in object) {
-   statements
-}
-
-


- 次の関数は、あるオブジェクトとそのオブジェクトの名前を引数にとります。そしてそのオブジェクトの全プロパティに対して反復し、プロパティ名とその値のリストにした文字列を返します。

-
function dump_props(obj, obj_name) {
-   var result = "";
-   for (var i in obj) {
-      result += obj_name + "." + i + " = " + obj[i] + "<br>";
-   }
-   result += "<hr>";
-   return result;
-}
-
-

make および model というプロパティを持つ car というオブジェクトでは次のような結果が得られます。

-
car.make = Ford
-car.model = Mustang
-
-

配列
- Array の要素に対して反復する方法としてこれを用いることは魅力的かもしれませんが、for...in 文はその配列の要素に加えてユーザ定義プロパティに対して繰り返すため、独自のプロパティやメソッドを追加するなどして Array オブジェクトに変更を加えると for...in 文は数値のインデックスに加えてユーザ定義プロパティの名前を返します。したがって、配列に対して反復したいときには数値のインデックスを用いた従来の for ループを使用したほうがいいでしょう。

-

for each...in 文

-

for each...inJavaScript 1.6 で導入されるループ文です。これは for...in に似ていますが、オブジェクトのプロパティの名前ではなく、プロパティの値に対して反復します。

-

with 文

-

with 文はデフォルトのオブジェクトについて文のセットを実行します。JavaScript はその文のセットにおいて非修飾名を検索し、その名前がデフォルトのオブジェクトのプロパティであるかを決定します。非修飾名がプロパティにマッチすると、そのプロパティがその文で使われます。そうでない場合はローカル変数かグローバル変数が使われます。

-

with 文は次のように使用します。

-
with (object) {
-   statements
-}
-
-


- 次の with 文では Math オブジェクトがデフォルトのオブジェクトに指定されています。with 文内の文は PI プロパティや cos および sin メソッドを参照していますが、オブジェクトは指定していません。JavaScript はこれらの参照は Math オブジェクトへのものであると想定します。

-
var a, x, y;
-var r = 10;
-with (Math) {
-   a = PI * r * r;
-   x = r * cos(PI);
-   y = r * sin(PI/2);
-}
-
-

注意:with 文を使うことでプログラムをより簡潔にすることができますが、with の不適切な使用はプログラムを大幅にスローダウンさせることに繋がります。Core JavaScript 1.5 Reference:Statements:with を参照してください。

- -

{{ PreviousNext("JavaScript/Guide/Loop_Statements/continue_Statement", "JavaScript/Guide/Comments") }}

diff --git a/files/ja/web/javascript/guide/objects_and_properties/index.html b/files/ja/web/javascript/guide/objects_and_properties/index.html deleted file mode 100644 index f2679c1d00..0000000000 --- a/files/ja/web/javascript/guide/objects_and_properties/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: オブジェクトとプロパティ -slug: Web/JavaScript/Guide/Objects_and_Properties ---- -

オブジェクトとプロパティ

-

JavaScript のオブジェクトには、それに結びつけられたプロパティがあります。簡単な記法でオブジェクトのプロパティにアクセスできます。

-
objectName.propertyName
-
-

オブジェクト名もプロパティ名も大文字と小文字を区別します。プロパティの定義は、そのプロパティに値を代入することで行います。例えば、myCar という名前のオブジェクトがあるとします(今回はオブジェクトが既に存在していると仮定)。次のようにして、そのオブジェクトに makemodelyear という名前のプロパティをそれぞれ作成することができます。

-
myCar.make = "Ford";
-myCar.model = "Mustang";
-myCar.year = 1969;
-
-

配列はある単一の変数名に結びつけられた値の順序集合です。JavaScript におけるプロパティと配列は密接に関連しています。事実、それらは同一のデータ構造への異なるインタフェースなのです。そのため、例えば次のようにして myCar オブジェクトのプロパティにアクセスすることができます。

-
myCar["make"] = "Ford";
-myCar["model"] = "Mustang";
-myCar["year"] = 1969;
-
-

この手の配列は連想配列として知られています。それぞれのインデックスの要素が文字列にも結びつけられているからです。これがどう動作するかというと、次の関数は引数としてオブジェクトとそのオブジェクトの名前を渡すとオブジェクトのプロパティを表示します。

-
function show_props(obj, obj_name) {
-   var result = "";
-   for (var i in obj)
-      result += obj_name + "." + i + " = " + obj[i] + "\n";
-   return result;
-}
-
-

関数 show_props(myCar, "myCar") を呼び出すと以下の結果が返されます。

-
myCar.make = Ford
-myCar.model = Mustang
-myCar.year = 1969
-
-

{{ PreviousNext("JavaScript/Guide/Predefined_Functions/escape_and_unescape_Functions", "JavaScript/Guide/Creating_New_Objects") }}

diff --git a/files/ja/web/javascript/guide/obsolete_pages/index.html b/files/ja/web/javascript/guide/obsolete_pages/index.html deleted file mode 100644 index 88bf9acbe7..0000000000 --- a/files/ja/web/javascript/guide/obsolete_pages/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Obsolete Pages -slug: Web/JavaScript/Guide/Obsolete_Pages -translation_of: Web/JavaScript/Guide -translation_of_original: Web/JavaScript/Guide/Obsolete_Pages ---- -

This is a list of pages that have been merged into chapters (in alphabetical order):

- - -
{{tree}}
diff --git a/files/ja/web/javascript/guide/obsolete_pages/predefined_core_objects/function_object/index.html b/files/ja/web/javascript/guide/obsolete_pages/predefined_core_objects/function_object/index.html deleted file mode 100644 index 79c30b670a..0000000000 --- a/files/ja/web/javascript/guide/obsolete_pages/predefined_core_objects/function_object/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Function Object -slug: Web/JavaScript/Guide/Obsolete_Pages/Predefined_Core_Objects/Function_Object ---- -

 

-

Function オブジェクト

-

定義済みの Function オブジェクトは、関数としてコンパイルさせたい JavaScript コードの文字列を指定します。

-

Function オブジェクトを作成するには次のようにします。

-
functionObjectName = new Function ([arg1, arg2, ... argn], functionBody)
-
-

functionObjectName は変数名または既存のオブジェクトのプロパティ名です。オブジェクトに小文字のイベントハンドラ名を続けて、window.onerror のようにして指定することもできます。

-

arg1, arg2, ... argn は関数が仮引数名として使用する引数です。それぞれが JavaScript の識別子として妥当な文字列である必要があります。例えば、"x" や "theForm" などです。

-

functionBody は関数の本体としてコンパイルさせたい JavaScript コードを表す文字列です。

-

Function オブジェクトはそれが使用されるたびに評価されます。これは関数を宣言し、それをコード内で呼び出す方法よりも非効率的です。宣言された関数はコンパイルされるからです。

-

ここで説明した関数の定義方法に加えて、function 文と関数式を用いることもできます。詳しくは コア JavaScript 1.5 リファレンス を参照してください。

-

次のコードは関数を変数 setBGColor に代入します。この関数は開いている文書の背景色をセットします。

-
var setBGColor = new Function("document.bgColor='antiquewhite'")
-
-

Function オブジェクトを呼び出すには、それがあたかも関数であるかのように変数名を指定すればいいのです。次のコードは setBGColor 変数で指定された関数を実行します。

-
var colorChoice="antiquewhite"
-if (colorChoice=="antiquewhite") {setBGColor()}
-
-

次のどちらかの方法を使用することでイベントハンドラに関数を代入することができます。

-
1. document.form1.colorButton.onclick=setBGColor
-2. <INPUT NAME="colorButton" TYPE="button"
-      VALUE="Change background color"
-      onClick="setBGColor()">
-
-

上記の変数 setBGColor を作成することは次の関数を宣言することと同じようなことです。

-
function setBGColor() {
-   document.bgColor='antiquewhite'
-}
-
-

関数を変数に代入することは関数を宣言することと似ていますが、異なる点もあります。

- -

関数を関数の中に入れ子にすることができます。内側の関数は外側の関数に対してプライベートになります。

- -

{{ PreviousNext("Core_JavaScript_1.5_Guide:Predefined_Core_Objects:Date_Object", "Core_JavaScript_1.5_Guide:Predefined_Core_Objects:Math_Object") }}

diff --git a/files/ja/web/javascript/guide/operators/arithmetic_operators/index.html b/files/ja/web/javascript/guide/operators/arithmetic_operators/index.html deleted file mode 100644 index 4aa9662292..0000000000 --- a/files/ja/web/javascript/guide/operators/arithmetic_operators/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: 算術演算子 -slug: Web/JavaScript/Guide/Operators/Arithmetic_Operators ---- -

算術演算子

-

算術演算子は、そのオペランドに数値(リテラルか変数)をとり、1 つの数値を返します。標準的な算術演算子は、加算 (+)、減算 (-)、乗算 (*)、除算 (/) です。これらの演算子は他のほとんどのプログラミング言語と同じように機能しますが、そのときの数値は、浮動小数点数として扱われます(0 で除算した結果は、NaN になることにも注意してください)。

-
1 / 2 // JavaScript では 0.5 を返す
-1 / 2 // Java では 0 を返す(どちらの数も浮動小数点数として明記されていない)
-
-1.0 / 2.0  // JavaScript でも Java でも 0.5 を返す
-
-

さらに、JavaScript では以下の表で示された算術演算子も使用できます。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
演算子説明
%
- (モジュロ)
2 項演算子。2 つのオペランドで除算したときの整数の余りを返す。12 % 5 は 2 を返す。
++
- (インクリメント)
単項演算子。オペランドに 1 を加える。前置演算子 (++x) を使った場合、オペランドに 1 を加えた後にその値を返す。後置演算子 (x++) を使った場合、オペランドに 1 を加える前にその値を返す。x が 3 のとき、++xx に 4 をセットし、4 を返す。一方、x++x に 4 をセットし、3 を返す。
--
- (デクリメント)
単項演算子。オペランドから 1 を引く。戻り値はインクリメント演算子のものと同様。x が 3 のとき、--xx に 2 をセットし、2 を返す。一方、x--x に 2 をセットし、3 を返す。
-
- (符号反転)
単項演算子。オペランドの符号を反転してその値を返す。x が 3 のとき、-x は -3 を返す。
-

表 3.4:算術演算子

-

{{ PreviousNext("JavaScript/Guide/Operators/Comparison_Operators", "JavaScript/Guide/Operators/Bitwise_Operators") }}

diff --git a/files/ja/web/javascript/guide/operators/assignment_operators/index.html b/files/ja/web/javascript/guide/operators/assignment_operators/index.html deleted file mode 100644 index 88a0b0beb7..0000000000 --- a/files/ja/web/javascript/guide/operators/assignment_operators/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: 代入演算子 -slug: Web/JavaScript/Guide/Operators/Assignment_Operators ---- -

代入演算子

-

代入演算子は、右のオペランドの値に基づいた値を左のオペランドに代入します。基本的な代入演算子はイコール (=) ですが、これは右のオペランドの値を左のオペランドに代入します。すなわち、x = y では y の値を x に代入します。

-

他の代入演算子は標準的な演算をするための短縮表記があります。次の表でそれを示します。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
短縮表記した演算子意味
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x <<= yx = x << y
x >>= yx = x >> y
x >>>= yx = x >>> y
x &= yx = x & y
x ^= yx = x ^ y
x |= yx = x | y
-

表 3.2:代入演算子

-

{{ PreviousNext("JavaScript/Guide/Operators", "JavaScript/Guide/Operators/Comparison_Operators") }}

diff --git a/files/ja/web/javascript/guide/operators/comparison_operators/index.html b/files/ja/web/javascript/guide/operators/comparison_operators/index.html deleted file mode 100644 index 182802bb5a..0000000000 --- a/files/ja/web/javascript/guide/operators/comparison_operators/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: 比較演算子 -slug: Web/JavaScript/Guide/Operators/Comparison_Operators ---- -

比較演算子

-

This seems to me kind of poorly explained, mostly the diference betwen "==" and "==="... 比較演算子は、オペランドを比較し、比較結果に基づいた論理値を返します。オペランドには数値、文字列、論理値、オブジェクトが使用できます。文字列は、Unicode 値を用いて標準的な辞書順に基づいて比較されます。ほとんどの場合、2 つのオペランドが異なる型ならば JavaScript はそのオペランドを比較に適した型に変換しようとします(このルールの唯一の例外は === および !== であり、これらは厳密に等値か否かを判断し、等値性をチェックする前にオペランドを適合する型に変換するということはありません)。これは一般に数値の比較が実行されることになります。次の表では比較演算子について説明します。次のコードで考えます。

-
var var1 = 3, var2 = 4;
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
演算子説明true を返す例
等しい (==)オペランドが等しい場合に true を返す。3 == var1
-

"3" == var1

- 3 == '3'
等しくない (!=)オペランドが等しくない場合に true を返す。var1 != 4
- var2 != "3"
厳密に等しい (===)オペランドが等しく、かつ同じ型である場合に true を返す。3 === var1
厳密には等しくない (!==)オペランドが等しくなく、かつ/または同じ型でない場合に true を返す。var1 !== "3"
- 3 !== '3'
より大きい (>)左のオペランドが右のオペランドよりも大きい場合に true を返す。var2 > var1
- "12" > 2
以上 (>=)左のオペランドが右のオペランド以上である場合に true を返す。var2 >= var1
- var1 >= 3
より小さい (<)左のオペランドが右のオペランドよりも小さい場合に true を返す。var1 < var2
- "12" < "2"
以下 (<=)左のオペランドが右のオペランド以下である場合に true を返す。var1 <= var2
- var2 <= 5
-

表 3.3:比較演算子

-

{{ PreviousNext("JavaScript/Guide/Operators/Assignment_Operators", "JavaScript/Guide/Operators/Arithmetic_Operators")}}

diff --git a/files/ja/web/javascript/guide/operators/logical_operators/index.html b/files/ja/web/javascript/guide/operators/logical_operators/index.html deleted file mode 100644 index fa6fa08068..0000000000 --- a/files/ja/web/javascript/guide/operators/logical_operators/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: 論理演算子 -slug: Web/JavaScript/Guide/Operators/Logical_Operators ---- -

論理演算子

-

論理演算子では基本的に真偽(論理)値を用います。そのような値があると真偽値を返します。しかし、&& および || 演算子は実際には指定されたオペランドの一方の値を返します。そのため、非真偽値とともに論理演算子が使われると非真偽値を返します。論理演算子について次の表で説明します。

- - - - - - - - - - - - - - - - - - - - - - - -
演算子使用法説明
&&expr1 && expr2(論理 AND)expr1 を false と見ることができる場合は expr1 を返す。そうでない場合は expr2 を返す。したがって、真偽値が使われた場合、両オペランドが true の場合は && は true を返し、そうでない場合は false を返す。
||expr1 || expr2(論理 OR)expr1 を true と見ることができる場合は expr1 を返す。そうでない場合は expr2 を返す。したがって、真偽値が使われた場合、どちらかのオペランドが true の場合は || は true を返し、両方とも false の場合は false を返す。
!!expr(論理 NOT)オペランドを true と見ることができる場合は false を返す。そうでない場合は true を返す。
-

表 3.7:論理演算子

-

false と見ることができる式とは、null、0、空文字列 ("")、または undefined に評価される式のことです。

-

以下のコードで &&(論理 AND)演算子の例を示します。

-
a1=true && true       // t && t は true を返す
-a2=true && false      // t && f は false を返す
-a3=false && true      // f && t は false を返す
-a4=false && (3 == 4)  // f && f は false を返す
-a5="Cat" && "Dog"     // t && t は Dog を返す
-a6=false && "Cat"     // f && t は false を返す
-a7="Cat" && false     // t && f は false を返す
-
-

以下のコードで ||(論理 OR)演算子の例を示します。

-
o1=true || true       // t || t は true を返す
-o2=false || true      // f || t は true を返す
-o3=true || false      // t || f は true を返す
-o4=false || (3 == 4)  // f || f は false を返す
-o5="Cat" || "Dog"     // t || t は Cat を返す
-o6=false || "Cat"     // f || t は Cat を返す
-o7="Cat" || false     // t || f は Cat を返す
-
-

以下のコードで !(論理 NOT)演算子の例を示します。

-
n1=!true              // !t は false を返す
-n2=!false             // !f は true を返す
-n3=!"Cat"             // !t は false を返す
-
-

ショートサーキット評価

-

論理式は左から右に評価されるため、以下のルールを用いることで「ショートサーキット」評価ができるようになっています。

- -

論理のルールはこれらの評価が常に正確であることを保証しています。上記の式の anything の部分は評価されないため、何らかの副作用が生じないように注意してください。

-

{{ PreviousNext("JavaScript/Guide/Operators/Bitwise_Operators", "JavaScript/Guide/Operators/String_Operators") }}

diff --git a/files/ja/web/javascript/guide/operators/special_operators/index.html b/files/ja/web/javascript/guide/operators/special_operators/index.html deleted file mode 100644 index 226faf2b3c..0000000000 --- a/files/ja/web/javascript/guide/operators/special_operators/index.html +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: 特殊演算子 -slug: Web/JavaScript/Guide/Operators/Special_Operators ---- -

特殊演算子

-

JavaScript は以下の特殊演算子があります。

- -

条件演算子

-

条件演算子は JavaScript では唯一の 3 つのオペランドをとる演算子です。演算子は条件に基づいて 2 つの値のうち、1 つを選択します。構文は次のとおりです。

-
condition ? val1 : val2
-
-

condition が true の場合、演算子は val1 の値を選択します。そうでない場合は val2 の値を選択します。標準的な演算子が使用できる場所でならどこででも条件演算子を使用することができます。

-

例えば、

-
status = (age >= 18) ? "adult" : "minor"
-
-

この文では、age が 18 以上の場合 "adult" という値を変数 status に代入します。そうでない場合は "minor" という値を status に代入します。

-

コンマ演算子

-

コンマ演算子 (,) は単に両方のオペランドを評価し、第 2 のオペランドの値を返します。この演算子は主に for ループ内で使用されます。このことでループのたびに複数の変数を更新できるようになります。

-

例えば、a が一辺が 10 要素の 2 次元配列のとき、以下のコードではコンマ演算子を用いることで 2 変数を同時にインクリメントしています。このコードでは配列の対角成分の値を出力します。

-
for (var i=0, j=9; i <= 9; i++, j--)
-   document.writeln("a["+i+"]["+j+"]= " + a[i][j])
-
-

delete

-

delete 演算子はオブジェクトやオブジェクトのプロパティ、配列の指定されたインデックスの要素を削除します。構文は以下のとおりです。

-
delete objectName
-delete objectName.property
-delete objectName[index]
-delete property // with 文内でのみ有効
-
-

ここで、objectName はオブジェクトの名前を、property は既存のプロパティを、index は配列の要素の位置を表す整数をそれぞれ表しています。

-

4 番目の形式は with 文内でのみ有効で、これはあるオブジェクトからプロパティを削除します。

-

delete 演算子を使うことで暗黙的に宣言された変数を削除することができますが、var 文を用いて宣言された変数は削除できません。

-

delete 演算子が成功すると、そのプロパティや要素には undefined がセットされます。また、演算が可能な場合は delete 演算子は true を返します。演算が不可能な場合は false を返します。

-
x=42
-var y= 43
-myobj=new Number()
-myobj.h=4      // プロパティ h を作成
-delete x       // true を返す(暗黙的に宣言されているならば削除可能)
-delete y       // false を返す(var 付きで宣言されているなら削除不可能)
-delete Math.PI // false を返す(定義済みプロパティは削除不可能)
-delete myobj.h // true を返す(ユーザ定義プロパティは削除可能)
-delete myobj   // true を返す(暗黙的に宣言されているならば削除可能)
-
-

配列要素の削除
- 配列要素を削除したとき、配列の長さには影響を及ぼしません。例えば a{{ mediawiki.external(3) }} を削除したとき、a{{ mediawiki.external(4) }} は依然 a{{ mediawiki.external(4) }} のままで、a{{ mediawiki.external(3) }} は undefined になります。

-

delete 演算子で配列要素を除去すると、もうその要素はその配列からなくなります。次の例では tree{{ mediawiki.external(3) }} は delete によって除去されます。

-
trees=new Array("redwood","bay","cedar","oak","maple")
-delete trees[3]
-if (3 in trees) {
-   // ここは実行されない
-}
-
-

配列要素は存在させたいが、値は未定義にしたいという場合は、delete 演算子の代わりに undefined キーワードを使用してください。次の例では trees{{ mediawiki.external(3) }} には undefined という値が代入されますが、その配列要素は存在したままになります。

-
trees=new Array("redwood","bay","cedar","oak","maple")
-trees[3]=undefined
-if (3 in trees) {
-   // ここは実行される
-}
-
-

in

-

in 演算子は、指定されたプロパティが指定されたオブジェクトにある場合に true を返します。構文は以下のとおりです。

-
propNameOrNumber in objectName
-
-

ここで、propNameOrNumber はプロパティ名か配列のインデックスを表す文字列式または数値式を、objectName はオブジェクトの名前をそれぞれ表しています。

-

次の例では in 演算子の使用法を示します。

-
// 配列
-trees=new Array("redwood","bay","cedar","oak","maple")
-0 in trees        // true を返す
-3 in trees        // true を返す
-6 in trees        // false を返す
-"bay" in trees    // false を返す(インデックスの指す値ではなく、
-                  // インデックスの数字を指定しなければならない)
-"length" in trees // true を返す(length は Array のプロパティ)
-
-// 定義済みオブジェクト
-"PI" in Math          // true を返す
-myString=new String("coral")
-"length" in myString  // true を返す
-
-// ユーザ定義オブジェクト
-mycar = {make:"Honda",model:"Accord",year:1998}
-"make" in mycar  // true を返す
-"model" in mycar // true を返す
-
-

instanceof

-

instanceof 演算子は、指定されたオブジェクトが指定されたオブジェクトの種類である場合に true を返します。構文は次のとおりです。

-
objectName instanceof objectType
-
-

ここで、objectNameobjectType と比較するオブジェクトの名前を、objectTypeDateArray のようなオブジェクトの種類をそれぞれ表しています。

-

実行時にオブジェクトの種類を確認する必要があるときは instanceof を使用してください。例えば、例外を受け取るとき、投げられた例外の種類によって別々の例外を扱うコードに分岐させることができます。

-

例えば、次のコードでは instanceof を使用することで theDayDate オブジェクトであるかどうかを決定しています。theDayDate オブジェクトなので if 文の中の文は実行されます。

-
theDay=new Date(1995, 12, 17)
-if (theDay instanceof Date) {
-   // 実行される文
-}
-
-

new

-

new 演算子は、ユーザ定義オブジェクトや、ArrayBooleanDateFunctionImageNumberObjectOptionRegExpString といった定義済みオブジェクトのインスタンスを作成するのに使用します。サーバでは DbPoolLockFileSendMail といったオブジェクトも使用できます。new の使用法は以下のとおりです。

-
objectName = new objectType ( param1 [,param2] ...[,paramN] )
-
-

オブジェクト初期化子を使用してもオブジェクトを作成することができます。オブジェクト初期化子の使用 にて説明しています。

-

詳しくはコア JavaScript リファレンスの new 演算子 のページを参照してください。

-

this

-

this キーワードを使うことでカレントオブジェクトを参照することができます。一般に this はあるメソッド内でそのメソッドを呼び出したオブジェクトを参照します。使用法は以下のとおりです。

-
this[.propertyName]
-
-

例 1
- あるオブジェクトの value プロパティの妥当性を確認する validate という関数を想定します。関数にはそのオブジェクトと、上限および下限の値を渡します。

-
function validate(obj, lowval, hival) {
-   if ((obj.value < lowval) || (obj.value > hival))
-      alert("Invalid Value!")
-}
-
-

各フォーム要素の onChange イベントハンドラにおいて validate を呼び出します。this を使うことでフォーム要素を渡すことができます。次の例をご覧ください。

-
<B>Enter a number between 18 and 99:</B>
-<INPUT TYPE = "text" NAME = "age" SIZE = 3
-   onChange="validate(this, 18, 99)">
-
-

例 2
- form プロパティと組み合わせると this でカレントオブジェクトの親のフォームを参照できます。次の例では、myForm というフォームに Text オブジェクトとボタンが格納されています。ユーザがボタンをクリックすると、Text オブジェクトの値にフォーム名がセットされます。ボタンの onClick イベントハンドラは this.form を利用して親のフォームである myForm を参照します。

-
<FORM NAME="myForm">
-Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
-<P>
-<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
-   onClick="this.form.text1.value=this.form.name">
-</FORM>
-
-

typeof

-

typeof 演算子は次の方法のうち、どちらかの方法で使用します。

-
1. typeof operand
-2. typeof (operand)
-
-

typeof 演算子は、未評価のオペランドの型を指す文字列を返します。operand は返される型を調べる対象となる文字列、変数、キーワード、オブジェクトです。括弧はあってもなくてもかまいません。

-

以下の変数を定義することを想定します。

-
var myFun = new Function("5+2")
-var shape="round"
-var size=1
-var today=new Date()
-
-

typeof 演算子はこれらの変数に対して以下の結果を返します。

-
typeof myFun is function
-typeof shape is string
-typeof size is number
-typeof today is object
-typeof dontExist is undefined
-
-

truenull というキーワードに対して、typeof 演算子は以下の結果を返します。

-
typeof true is boolean
-typeof null is object
-
-

数値や文字列に対して、typeof 演算子は以下の結果を返します。

-
typeof 62 is number
-typeof 'Hello world' is string
-
-

プロパティ値に対して、typeof 演算子はプロパティ値の型を返します。

-
typeof document.lastModified is string
-typeof window.length is number
-typeof Math.LN2 is number
-
-

メソッドや関数に対して、typeof 演算子は以下の結果を返します。

-
typeof blur is function
-typeof eval is function
-typeof parseInt is function
-typeof shape.split is function
-
-

定義済みオブジェクトに対して、typeof 演算子は以下の結果を返します。

-
typeof Date is function
-typeof Function is function
-typeof Math is function
-typeof Option is function
-typeof String is function
-
-

void

-

void 演算子は次の方法のうち、どちらかの方法で使用します。

-
1. void (expression)
-2. void expression
-
-

void 演算子は値を返さずに評価する式を指定します。expression は評価する JavaScript の式です。式の周りの括弧はあってもなくてもかまいませんが、使用したほうが見た目はいいです。

-

void 演算子を使用することで式をハイパーテキストリンクとして指定することができます。式は評価されますが、開いている文書の代わりに読み込まれるということはありません。

-

以下のコードはユーザがクリックしても何も起こらないハイパーテキストリンクを作成します。ユーザがリンクをクリックすると void(0) は undefined に評価され、JavaScript としては影響を及ぼしません。

-
<A HREF="javascript:void(0)">Click here to do nothing</A>
-
-

以下のコードはユーザがクリックするとフォームが送信されるハイパーテキストリンクを作成します。

-
<A HREF="javascript:void(document.form.submit())">
-Click here to submit</A>
-
-

{{ PreviousNext("JavaScript/Guide/Operators/String_Operators", "JavaScript/Guide/Creating_a_Regular_Expression") }}

diff --git a/files/ja/web/javascript/guide/operators/string_operators/index.html b/files/ja/web/javascript/guide/operators/string_operators/index.html deleted file mode 100644 index 41bf8bbc44..0000000000 --- a/files/ja/web/javascript/guide/operators/string_operators/index.html +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: 文字列演算子 -slug: Web/JavaScript/Guide/Operators/String_Operators ---- -

文字列演算子

-

比較演算子は文字列に使用できますが、これに加えて 2 つの文字列を結合する結合演算子 (+) も使用できます。これは 2 つのオペランドの文字列を結合した文字列を返します。例えば、"my " + "string""my string" という文字列を返します。

-

短縮表記した代入演算子 += も文字列の結合に使用できます。例えば、変数 mystring に "alpha" という値が格納されているとき、式 mystring += "bet" の評価結果は "alphabet" となり、この値を mystring に代入します。

-

{{ PreviousNext("JavaScript/Guide/Operators/Logical_Operators", "JavaScript/Guide/Operators/Special_Operators") }}

diff --git a/files/ja/web/javascript/guide/predefined_functions/escape_and_unescape_functions/index.html b/files/ja/web/javascript/guide/predefined_functions/escape_and_unescape_functions/index.html deleted file mode 100644 index aecb8a81f1..0000000000 --- a/files/ja/web/javascript/guide/predefined_functions/escape_and_unescape_functions/index.html +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: escape 関数と unescape 関数 -slug: Web/JavaScript/Guide/Predefined_Functions/escape_and_unescape_Functions ---- -
-

escape および unescape 関数

-

escape および unescape 関数は文字列をエンコードしたりデコードしたりします。escape 関数は ISO Latin 文字セットで表された引数の 16 進エンコーディングを返します。unescape は指定した 16 進エンコーディングの値に対する ASCII 文字列を返します。

-

これらの関数の構文は以下のとおりです。

-
escape(string)
-unescape(string)
-
-

これらの関数は主にサーバサイド JavaScript で URL 中の名前と値のペアのエンコードやデコードに使用されます。

- escape および unescape 関数は 非 ASCII 文字に対しては正しく機能せず、廃止予定になっています。JavaScript 1.5 以降では encodeURIdecodeURIencodeURIComponent および decodeURIComponent を使用してください。
-

{{ PreviousNext("JavaScript/Guide/Predefined_Functions/Number_and_String_Functions", "JavaScript/Guide/Objects_and_Properties") }}

diff --git a/files/ja/web/javascript/guide/predefined_functions/eval_function/index.html b/files/ja/web/javascript/guide/predefined_functions/eval_function/index.html deleted file mode 100644 index 3945955e86..0000000000 --- a/files/ja/web/javascript/guide/predefined_functions/eval_function/index.html +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: eval 関数 -slug: Web/JavaScript/Guide/Predefined_Functions/eval_Function ---- -
-

eval 関数

-

eval 関数は JavaScript のコードの文字列を特定のオブジェクトを参照することなく評価します。eval の構文は次のとおりです。

-
eval(expr)
-
-

ここで expr は評価される文字列です。

- 文字列が式を表している場合は eval はその式を評価します。また、1 つ以上の JavaScript の文を表している場合は eval はその式を実行します。eval のコードのスコープは呼び出し元コードのスコープと同じです。演算式を評価するために eval を呼び出さないでください。JavaScript は自動的に演算式を評価します。
-

{{ PreviousNext("JavaScript/Guide/Predefined_Functions", "JavaScript/Guide/Predefined_Functions/isFinite_Function") }}

diff --git a/files/ja/web/javascript/guide/predefined_functions/index.html b/files/ja/web/javascript/guide/predefined_functions/index.html deleted file mode 100644 index 758c6f22a0..0000000000 --- a/files/ja/web/javascript/guide/predefined_functions/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 定義済み関数 -slug: Web/JavaScript/Guide/Predefined_Functions ---- -
-

定義済み関数

-

JavaScript にはトップレベルの定義済み関数がいくつかあります。

- -
-

{{ PreviousNext("JavaScript/Guide/Using_the_arguments_object", "JavaScript/Guide/Predefined_Functions/eval_Function") }}

diff --git a/files/ja/web/javascript/guide/the_employee_example/creating_the_hierarchy/index.html b/files/ja/web/javascript/guide/the_employee_example/creating_the_hierarchy/index.html deleted file mode 100644 index 2340536ff7..0000000000 --- a/files/ja/web/javascript/guide/the_employee_example/creating_the_hierarchy/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Creating the Hierarchy -slug: Web/JavaScript/Guide/The_Employee_Example/Creating_the_Hierarchy ---- -

階層の作成

-

Employee の階層を実装するための適当なコンストラクタ関数を定義する方法はいくつかあります。これの定義に何を選択するかは、アプリケーションで何ができるようにしたいかに大きくよります。

-

このセクションではとても単純(かつ比較的柔軟でない)定義の使用方法を示し、継承を機能させる方法を実際に示します。これらの定義では、オブジェクト作成時に何らかのプロパティの値を指定することはできません。新しく作成されるオブジェクトは単にデフォルトの値を取得するだけです。これは後から変更できます。図 8.2 ではこれらの単純な定義を備えた階層を例示します。

-

実際のアプリケーションでは、オブジェクト作成時にプロパティの値を設定できるようにするコンストラクタを定義することになるでしょう(詳しくは より柔軟なコンストラクタ を参照)。今回はこれらの単純な定義を使用して、継承はどのようにして起こるのかを実際に示していくことにします。

-

Image:hier02.gif
- 図 8.2:Employee オブジェクトの定義

-

以下に示すように、Java と JavaScript の Employee の定義は似ています。唯一の相違点は、Java では各プロパティに対して型を指定する必要があるのに対して、JavaScript ではその必要がないことです。また、Java のクラスでは明示的なコンストラクタメソッドを作成する必要があります。

- - - - - - - - - - - -
JavaScriptJava
-
-function Employee () {
-this.name = "";
-this.dept = "general";
-}
-
-
-
-public class Employee {
-   public String name;
-   public String dept;
-   public Employee () {
-      this.name = "";
-      this.dept = "general";
-   }
-}
-
-
-

Manager および WorkerBee の定義では、継承の連鎖において上である次のオブジェクトの指定方法に違いがあります。JavaScript では原型的なインスタンスをコンストラクタ関数の prototype プロパティとして追加します。コンストラクタを定義した後ならいつでもそれをすることができます。Java ではクラス定義内でスーパークラスを指定します。クラス定義の外部でスーパークラスを変更することはできません。

- - - - - - - - - - - -
JavaScriptJava
-
-function Manager () {
-this.reports = [];
-}
-Manager.prototype = new Employee;
-
-function WorkerBee () {
-this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
-
-
-public class Manager extends Employee {
-   public Employee[] reports;
-   public Manager () {
-      this.reports = new Employee[0];
-   }
-}
-
-public class WorkerBee extends Employee {
-   public String[] projects;
-   public WorkerBee () {
-      this.projects = new String[0];
-   }
-}
-
-
-

Engineer および SalesPerson の定義は、WorkerBee の子孫、それゆえに Employee の子孫であるオブジェクトを作成します。これらの種類のオブジェクトは連鎖において上にある全オブジェクトのプロパティを持ちます。さらに、これらの定義は dept プロパティの継承された値をこれらのオブジェクト固有の新しい値で上書きします。

- - - - - - - - - - - -
JavaScriptJava
-
-function SalesPerson () {
-   this.dept = "sales";
-   this.quota = 100;
-}
-SalesPerson.prototype = new WorkerBee;
-
-function Engineer () {
-   this.dept = "engineering";
-   this.machine = "";
-}
-Engineer.prototype = new WorkerBee;
-
-
-
-public class SalesPerson extends WorkerBee {
-   public double quota;
-   public SalesPerson () {
-      this.dept = "sales";
-      this.quota = 100.0;
-   }
-}
-
-public class Engineer extends WorkerBee {
-   public String machine;
-   public Engineer () {
-      this.dept = "engineering";
-      this.machine = "";
-   }
-}
-
-
-

これらの定義を使用して、そのプロパティのデフォルト値を取得するこれらのオブジェクトのインスタンスを作成することができます。図 8.3 ではこれらの JavaScript の定義を使用して新しいオブジェクトを作成する方法を示しています。また、新しいオブジェクトに対するプロパティの値も示しています。

-

注意インスタンスという用語はクラスベース言語においてはある特定の技術的な意味を持っています。これらの言語では、インスタンスとはクラスの個々のメンバであり、クラスとは根本的に異なるものです。JavaScript では「インスタンス」はこの技術的な意味を持っていません。なぜならば JavaScript にはクラスとインスタンスとの間のこの違いがないからです。しかしながら、JavaScript について話す際に、「インスタンス」をある特定のコンストラクタ関数を用いて作成したオブジェクトを意味する言葉として正式ではない形で使用することがあります。例えば、janeEngineer のインスタンスであると砕けた言い方をすることもできます。同様に、祖先、そして子孫という用語は JavaScript において正式な意味を持ちませんが、プロトタイプチェーンにおいて上や下にあるオブジェクトについて言及する際にそれらを正式ではない形で使用してもかまいません。

-

Image:hier03.gif
- 図 8.3:単純な定義を用いたオブジェクトの作成

-
-

{{ PreviousNext("Core_JavaScript_1.5_Guide:The_Employee_Example", "Core_JavaScript_1.5_Guide:The_Employee_Example:Object_Properties") }}

-
diff --git a/files/ja/web/javascript/guide/the_employee_example/index.html b/files/ja/web/javascript/guide/the_employee_example/index.html deleted file mode 100644 index 63176fa7e2..0000000000 --- a/files/ja/web/javascript/guide/the_employee_example/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: The Employee Example -slug: Web/JavaScript/Guide/The_Employee_Example ---- -

従業員の例

-

この章の残りは次の図で示す従業員の階層を使用していきます。

-

Image:hier01.gif

-

図 8.1:単純なオブジェクト階層

-

これの例では以下のオブジェクトを使用しています。

- -

残りの例:

- -
-

{{ PreviousNext("Core_JavaScript_1.5_Guide:Class-Based_vs._Prototype-Based_Languages", "Core_JavaScript_1.5_Guide:The_Employee_Example:Creating_the_Hierarchy") }}

-
-

 

diff --git a/files/ja/web/javascript/guide/the_employee_example/object_properties/adding_properties/index.html b/files/ja/web/javascript/guide/the_employee_example/object_properties/adding_properties/index.html deleted file mode 100644 index c6d536602b..0000000000 --- a/files/ja/web/javascript/guide/the_employee_example/object_properties/adding_properties/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Adding Properties -slug: Web/JavaScript/Guide/The_Employee_Example/Object_Properties/Adding_Properties ---- -

プロパティの追加

-

JavaScript では実行時にどんなオブジェクトにもプロパティを追加することができます。コンストラクタ関数で与えられるプロパティだけを使う必要はありません。ある 1 つのオブジェクト固有のプロパティを追加するには、次のようにしてオブジェクトに値を代入します。

-
mark.bonus = 3000;
-
-

すると、mark オブジェクトには bonus プロパティができます。しかし、他のどの WorkerBee にもこのプロパティは存在しません。

-

あるコンストラクタ関数に対するプロトタイプとして使用されているオブジェクトに新しいプロパティを追加する場合、プロトタイプからプロパティを継承する全オブジェクトへそのプロパティを追加することになります。例えば、次の文を使用すると specialty プロパティをすべての従業員に対して追加することができます。

-
Employee.prototype.specialty = "none";
-
-

JavaScript がこの文を実行するとすぐに mark オブジェクトも "none" という値を持つ specialty プロパティを持つようになります。次の図ではこのプロパティを Employee プロトタイプに追加し、さらに Engineer プロトタイプに対するそれを上書きしたときの効果を示します。

-

Image:hier04.gif
- 図 8.4:プロパティの追加

-
-

{{ PreviousNext("Core_JavaScript_1.5_Guide:The_Employee_Example:Object_Properties:Inheriting_Properties", "Core_JavaScript_1.5_Guide:The_Employee_Example:More_Flexible_Constructors") }}

-
-

 

diff --git a/files/ja/web/javascript/guide/the_employee_example/object_properties/index.html b/files/ja/web/javascript/guide/the_employee_example/object_properties/index.html deleted file mode 100644 index e529b8bb52..0000000000 --- a/files/ja/web/javascript/guide/the_employee_example/object_properties/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Object Properties -slug: Web/JavaScript/Guide/The_Employee_Example/Object_Properties ---- -

オブジェクトのプロパティ

-

このセクションでは、プロトタイプチェーンにおいてオブジェクトが他のオブジェクトからどのようにプロパティを継承するのか、また、実行時にプロパティを追加すると何が起きるのかについて論じます。

- -
-

{{ PreviousNext("Core_JavaScript_1.5_Guide:The_Employee_Example:Creating_the_Hierarchy", "Core_JavaScript_1.5_Guide:The_Employee_Example:Object_Properties:Inheriting_Properties") }}

-
diff --git a/files/ja/web/javascript/guide/the_employee_example/object_properties/inheriting_properties/index.html b/files/ja/web/javascript/guide/the_employee_example/object_properties/inheriting_properties/index.html deleted file mode 100644 index 798746ead6..0000000000 --- a/files/ja/web/javascript/guide/the_employee_example/object_properties/inheriting_properties/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Inheriting Properties -slug: >- - Web/JavaScript/Guide/The_Employee_Example/Object_Properties/Inheriting_Properties ---- -

プロパティの継承

-

次の文を用いて(図 8.3 で示したように)mark オブジェクトを WorkerBee として作成するとします。

-
mark = new WorkerBee;
-
-

JavaScript は new 演算子に出くわすと、新しく汎用オブジェクトを生成し、この新しいオブジェクトを this キーワードの値として WorkerBee コンストラクタ関数に渡します。コンストラクタ関数は明示的に projects プロパティの値をセットします。さらに、内部的な __proto__ プロパティの値として WorkerBee.prototype の値をセットします。(このプロパティ名は最初と最後に 2 文字ずつのアンダースコアが付いています。)__proto__ プロパティはプロパティの値を返すのに使用されるプロトタイプチェーンを決定します。これらのプロパティがセットされると JavaScript は新しいオブジェクトを返し、代入文は変数 mark にそのオブジェクトをセットします。

-

このプロセスでは mark がプロトタイプチェーンから継承するプロパティとして明示的には mark オブジェクトに値(ローカルの値)を格納しません。プロパティの値を使用するとき、JavaScript はまずその値がそのオブジェクトに存在しているかどうかを確認します。存在している場合はその値が返されます。値がローカルには存在していない場合、JavaScript はプロトタイプチェーンを確認します(__proto__ プロパティを使用)。プロトタイプチェーン内のオブジェクトがそのプロパティの値を持っている場合、その値が返されます。そのようなプロパティが見つからない場合は JavaScript はそのオブジェクトにはそのプロパティがないと報告します。このようにして、mark オブジェクトには次のようなプロパティと値が入ることになります。

-
mark.name = "";
-mark.dept = "general";
-mark.projects = [];
-
-

mark オブジェクトは mark.__proto__ の原型的なオブジェクトから name および dept プロパティの値を継承します。WorkerBee コンストラクタによって projects プロパティにローカルの値が代入されます。このことでプロパティとその値を継承することができます。このプロセスの細かいところは プロパティの継承、再び にて議論します。

-

これらのコンストラクタにインスタンス固有の値を渡せないため、この情報は汎用的になります。プロパティの値は WorkerBee によって作成されるすべての新しいオブジェクトに共有される、デフォルトの値になります。もちろん、これらのどのプロパティのでもその値を変えることができます。そのためには次のようにして mark に固有の情報を与えます。

-
mark.name = "Doe, Mark";
-mark.dept = "admin";
-mark.projects = ["navigator"];
-
-
-

{{ PreviousNext("Core JavaScript 1.5 Guide:The Employee Example:Object Properties", "Core JavaScript 1.5 Guide:The Employee Example:Object Properties:Adding Properties") }}

-
diff --git a/files/ja/web/javascript/guide/using_the_arguments_object/index.html b/files/ja/web/javascript/guide/using_the_arguments_object/index.html deleted file mode 100644 index 10c2d9e3ff..0000000000 --- a/files/ja/web/javascript/guide/using_the_arguments_object/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: arguments オブジェクトの使用 -slug: Web/JavaScript/Guide/Using_the_arguments_object ---- -
-

arguments オブジェクトの使用

-

関数の引数は配列のようなオブジェクトで管理されます。関数内では、次のようにして渡された引数を指すことができます。

-
arguments[i]
-
-

ここで i は引数の順序を表す数を指します。これは 0 から始まります。関数に渡された第 1 引数は arguments{{ mediawiki.external(0) }} となります。引数のトータルの数は arguments.length で示されます。

-

arguments オブジェクトを使用すると、宣言時の仮引数の数よりも多くの引数を使って関数を呼び出すことができます。これはその関数に渡す引数の数が前もってわかっていない場合に役立ちます。arguments.length を使用することで実際にその関数に渡された引数の数を特定することができます。また、arguments オブジェクトを使用することで各引数を扱うことができます。

-

例えば、複数の文字列を連結する関数を考えます。この関数の仮引数は、連結するアイテムを区切るのに用いる文字列のみです。この関数は次のように定義されています。

-
function myConcat(separator) {
-   var result = ""; // リストを初期化する
-   // 引数について繰り返し
-   for (var i = 1; i < arguments.length; i++) {
-      result += arguments[i] + separator;
-   }
-   return result;
-}
-
-

この関数に引数をいくつも渡すことができます。そして各引数を文字列のリストに連結します。

-
// "red, orange, blue, " を返す
-myConcat(", ", "red", "orange", "blue");
-
-// "elephant; giraffe; lion; cheetah; " を返す
-myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
-
-// "sage. basil. oregano. pepper. parsley. " を返す
-myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
-
-

さらなる情報については、コア JavaScript リファレンスの Function オブジェクト をご覧ください。

-

JavaScript 1.3 以前のバージョン
- arguments オブジェクトは Function オブジェクトのプロパティであり、次のように関数の名前を前に付けることができます。

- functionName.arguments{{ mediawiki.external('i') }}
-

{{ PreviousNext("JavaScript/Guide/Calling_Functions", "JavaScript/Guide/Predefined_Functions") }}

diff --git a/files/ja/web/javascript/guide/variables/index.html b/files/ja/web/javascript/guide/variables/index.html deleted file mode 100644 index cebaecc949..0000000000 --- a/files/ja/web/javascript/guide/variables/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: 変数 -slug: Web/JavaScript/Guide/Variables ---- -

{{ 英語版章題("Variables") }}

-

変数

-

アプリケーションで値を識別する名前として変数を使用します。変数の名前はあるルールに従って付けなくてはなりません。変数の名前は識別子とも呼ばれます。

-

JavaScript の識別子は必ずアルファベットかアンダースコア (_) かドル記号 ($) から始まらなくてはなりません。続く文字は数字 (0-9) も使えます。JavaScript は大文字・小文字を区別するため、使えるアルファベットは "A" から "Z"(大文字)と "a" から "z"(小文字)です。

-

JavaScript 1.5 からは å や ü といった ISO 8859-1 や Unicode のアルファベットも識別子に使えます。Unicode エスケープシーケンス のページに列挙されている \uXXXX 形式の Unicode エスケープシーケンスも識別子に使用できます。

-

Number_hitstemp99_name が使用できる名前の例です。

-

{{ 英語版章題("Declaring Variables") }}

-

変数の宣言

-

2 つの方法で変数を宣言できます。

- -

{{ 英語版章題("Evaluating Variables") }}

-

変数の評価

-

var 文を使用し、初期化せずに宣言された変数は undefined の値をとります。

-

未宣言の変数にアクセスしようとすると、ReferenceError 例外が投げられます。

-
var a;
-print("a の値は " + a); // "a の値は undefined" を出力
-print("b の値は " + b); // ReferenceError 例外を投げる
-
-

undefined を使うと変数に値が入っているかどうかを確かめられます。以下のコードでは、変数 input には値が代入されておらず、if 文での評価結果は true です。

-
var input;
-if(input === undefined){
-  doThis();
-} else {
-  doThat();
-}
-
-

Not sure how the following is related to "Variables" section undefined は真偽値コンテキストで使用されると false として振る舞います。例えば以下のコードでは、myArray の要素が未定義であるために関数 myFunction が実行されます。

-
var myArray = new Array();
-if (!myArray[0]) myFunction();
-
-

null 変数を評価すると、数値コンテキストにおいては null 値は 0 として振る舞います。また、真偽値コンテキストでは false として振る舞います。

-
var n = null;
-print(n * 32); // prints 0
-
-

{{ 英語版章題("Variable Scope") }}

-

変数のスコープ

-

変数を関数の外側で宣言すると、その変数はその文書のどのコードからも使用できるようになるため、グローバル(大域)変数と呼ばれます。変数を関数の内部で宣言すると、その変数はその関数の中でしか使用できないため、ローカル(局所)変数と呼ばれます。

-

JavaScript には ブロック文 のスコープがありません。むしろ、そのブロックを内包しているコードに対して局所化されます。例えば以下のコードは conditionfalse のとき、例外を投げずに 0 が出力されます。

-
if (condition) {
-  var x = 5;
-}
-print(x ? x : 0);
-
-

JavaScript の変数に関する独特なこととして、後に宣言される変数を例外を発生させることなく参照できるというのも挙げられます。

-
print(x === undefined); // "true" を出力
-var x = 3;
-
-

{{ 英語版章題("Global Variables") }}

-

グローバル変数

-

need links to pages discussing scope chains and the global object グローバル変数は実際にはグローバルオブジェクトのプロパティです。ウェブページではグローバルオブジェクトは window です。そのため、window.variable という構文を使うことでグローバル変数をセットしたり、グローバル変数にアクセスしたりすることができます。

-

したがって、あるウィンドウやフレームで宣言したグローバル変数に、そのウィンドウやフレームの名前を指定すれば別のウィンドウやフレームからアクセスできます。例えば、phoneNumber という変数を FRAMESET 文書内で宣言すると、子フレームから parent.phoneNumber としてこの変数を参照することができます。

-

{{ 英語版章題("See Also") }}

-

関連項目

-

JavaScript のシャープ変数

-

{{ PreviousNext("JavaScript/Guide/Values", "JavaScript/Guide/Constants") }}

diff --git a/files/ja/web/javascript/guide/writing_a_regular_expression_pattern/index.html b/files/ja/web/javascript/guide/writing_a_regular_expression_pattern/index.html deleted file mode 100644 index 64da075317..0000000000 --- a/files/ja/web/javascript/guide/writing_a_regular_expression_pattern/index.html +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: 正規表現パターンの記述 -slug: Web/JavaScript/Guide/Writing_a_Regular_Expression_Pattern ---- -

正規表現パターンを書く

- -

正規表現パターンは、/abc/ のような単純な文字、または /ab*c//Chapter (\d+)\.\d*/ のような単純な文字と特殊文字との組み合わせからなります。最後の例では記憶装置として使われている丸括弧が含まれています。パターンのこの部分でなされたマッチは後で使用できるように記憶されます。詳しくは 括弧で囲まれた部分文字列のマッチの使用 を参照してください。

- -

単純なパターンの使用

- -

単純なパターンは、直接マッチしている部分を見つけたい文字で構成されます。例えば、/abc/ というパターンは、実際に 'abc' という文字が一緒にその順で存在しているときにだけ、文字列中の文字の組み合わせにマッチします。"Hi, do you know your abc's?" や "The latest airplane designs evolved from slabcraft." といった文字列でのマッチは成功します。どちらの場合でも 'abc' という部分文字列にマッチします。"Grab crab" という文字列では 'abc' という部分文字列が含まれていないためマッチしません。

- -

特殊文字の使用

- -

1 つ以上の b を見つけたり、ホワイトスペースを見つけたりといった直接マッチより高度なマッチの検索では、パターンに特殊文字を使用します。例えば /ab*c/ というパターンでは 1 つの 'a' とその後ろに続く 0 個以上の 'b'(* は直前のアイテムの 0 回以上の出現を意味する)とそのすぐ後ろに続く 'c' からなる文字の組み合わせにマッチします。"cbbabbbbcdebc" という文字列ではこのパターンは 'abbbbc' という部分文字列にマッチします。

- -

以下の表で正規表現で使用できる特殊文字とその意味を詳しく説明します。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
文字意味
\次のうちのどちらか。 -
    -
  • 通常は文字どおり扱われる文字に対して、次の文字は特殊であり、文字どおりに解釈すべきではないと指示する。例えば、/b/ は 'b' という文字にマッチする。b の前にバックスラッシュを置き、/\b/ とすると、その文字は単語の区切りにマッチすることを意味する特殊文字になる。
  • -
  • 通常は特殊文字として扱われる文字に対して、次の文字は特殊ではなく、文字どおりに解釈すべきであると指示する。例えば、* は直前のアイテムの 0 回以上の出現にマッチさせることを意味する特殊文字である。つまり、例えば /a*/ は a の 0 文字以上の a へのマッチを意味する。* という文字そのものにマッチさせるには、その直前にバックスラッシュを置く。例えば、/a\*/ は 'a*' にマッチする。
  • -
-
^入力の先頭にマッチする。複数行フラグが true にセットされている場合は、改行文字直後にもマッチする。 例えば、/^A/ は "an A" の 'A' にはマッチしないが、"An A" の最初の 'A' にはマッチする。
$入力の末尾にマッチする。複数行フラグが true にセットされている場合は、改行文字直前にもマッチする。 例えば、/t$/ は "eater" の 't' にはマッチしないが、"eat" の 't' にはマッチする。
*直前の文字の 0 回以上の繰り返しにマッチする。 例えば、/bo*/ は "A ghost booooed" の 'boooo' や "A bird warbled" の 'b' にはマッチするが、"A goat grunted" ではマッチしない。
+直前の文字の 1 回以上の繰り返しにマッチする。{1,} と同等。 例えば、/a+/ は "candy" の 'a' や、"caaaaaaandy" のすべての a にマッチする。
?直前の文字の 0 回か 1 回の繰り返しにマッチする。 -

例えば、/e?le?/ は "angel" の 'el' や "angle" の 'le' にマッチする。

- -

*、+、?、{} といった量指定子の直後に使用した場合、その量指定子をスキップ優先(最小回数にマッチ)にする。これはデフォルトとは逆であり、デフォルトは繰り返し優先(最大回数にマッチ)。例えば、/\d+/ は非グローバルで "123abc" の "123" にマッチするが、/\d+?/ の場合、"1" だけにマッチする。

- 先読み表現内でも使用できるが、これはこの表の x(?=y) および x(?!y) にて説明。
.小数点は改行文字以外のどの 1 文字にもマッチする。 例えば、/.n/ は "nay, an apple is on the tree" の 'an' や 'on' にはマッチするが、'nay' にはマッチしない。
(x)'x' にマッチし、マッチしたものを記憶しておく。これはキャプチャする括弧と呼ぶ。 例えば、/(foo)/ は "foo bar" の 'foo' にマッチし、これを記憶する。マッチした部分文字列は結果として生成される配列の要素 1, ..., b から参照できる。
(?:x)'x' にマッチするが、マッチしたものは記憶しない。これはキャプチャしない括弧と呼ぶ。マッチした部分文字列は先程のような配列の要素 1, ..., n から参照することはできない。
x(?=y)'x' に 'y' が続く場合のみ 'x' にマッチする。例えば、/Jack(?=Sprat)/ は 'Jack' の後ろに 'Sprat' が続く場合のみ 'Jack' にマッチする。/Jack(?=Sprat|Frost)/ は 'Jack' の後ろに 'Sprat' または 'Frost' が続く場合のみ 'Jack' にマッチする。しかしながら、'Sprat' も 'Frost' もマッチの結果には現れない。
x(?!y)'x' に 'y' が続かない場合のみ 'x' にマッチする。例えば、/\d+(?!\.)/ はある数に小数点が続かない場合のみその数にマッチする。正規表現 /\d+(?!\.)/.exec("3.141") は 141 にはマッチするが 3.141 にはマッチしない。
x|y'x' または 'y' にマッチする。 例えば、/green|red/ は "green apple" の "green' や "red apple" の 'red' にマッチする。
{n}n には正の整数が入る。直前の文字がちょうど n 回出現するものにマッチする。 例えば、/a{2}/ は "candy" の 'a' にはマッチしないが、"caandy" の すべての a にマッチする。また、"caaandy" の最初の 2 つの a にマッチする。
{n,}n には正の整数が入る。直前の文字が少なくとも n 回出現するものにマッチする。 例えば、/a{2,}/ は "candy" の 'a' にはマッチしないが、"caandy" や "caaaaaaandy" の すべての a にマッチする。
{n,m}n および m には正の整数が入る。直前の文字が少なくとも n 回、多くとも m 回出現するものにマッチする。 例えば、/a{1,3}/ は "cndy" ではマッチせず、"candy" の 'a'、"caandy" の最初の 2 つの a、"caaaaaaandy" の最初の 3 つの a にマッチする。"caaaaaaandy" では元の文字列に a が 4 つ以上あるが、マッチするのは "aaa" であることに注意。
[xyz]文字の集合。囲まれた文字のどれにでもマッチする。ハイフンを用いて文字の範囲を指定することも可能。 例えば、/[abcd]//[a-d]/ と同じ。これは "brisket" の 'b' や "city" の 'c' にマッチする。
[^xyz]文字の集合の否定または補集合。角括弧で囲まれていないものにマッチする。ハイフンを用いて文字の範囲を指定することも可能。 例えば、/[^abc]//[^a-c]/ と同じ。これは "brisket" の 'r' や "chop" の 'h' にマッチする。
[\b]後退にマッチする。(\b と混同してはならない。)
\bスペースや改行文字のような単語の区切りにマッチする。([\b] と混同してはならない。) 例えば、/\bn\w/ は "noonday" の 'no' にマッチする。また、/\wy\b/ は "possibly yesterday" の 'ly' にマッチする。
\B単語の区切り以外の文字にマッチする。 例えば、/\w\Bn/ は "noonday" の 'on' にマッチする。また、/y\B\w/ は "possibly yesterday" の 'ye' にマッチする。
\cXX には制御文字が入る。文字列中の制御文字にマッチする。 例えば、/\cM/ は文字列中の control-M にマッチする。
\d数字にマッチする。[0-9] と同等。 例えば、/\d//[0-9]/ は "B2 is the suite number" の '2' にマッチする。
\D数字以外の文字にマッチする。[^0-9] と同等。 例えば、/\D//[^0-9]/ は "B2 is the suite number" の 'B' にマッチする。
\f改ページにマッチする。
\n改行にマッチする。
\r復帰にマッチする。
\sスペース、タブ、改ページ、改行を含む、1 つのホワイトスペース文字にマッチする。 [ \f\n\r\t\v\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF] と同等。 例えば、/\s\w*/ は "foo bar" の ' bar' にマッチする。
\Sホワイトスペース以外の 1 文字にマッチする。[^ \f\n\r\t\v\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF] と同等。 例えば、/\S\w*/ は "foo bar" の 'foo' にマッチする。
\tタブにマッチする。
\v垂直タブにマッチする。
\wアンダースコアを含むどの英数字にもマッチする。[A-Za-z0-9_] と同等。 例えば、/\w/ は "apple" の 'a' や "$5.28" の '5' や "3D" の '3' にマッチする。
\W前述以外の文字にマッチする。[^A-Za-z0-9_] と同等。 例えば、/\W//[^$A-Za-z0-9_]/ は "50%" の '%' にマッチする。
\nn には正の整数が入る。その正規表現の n 番目の括弧の部分にマッチする最後の部分文字列への後方参照(左括弧をカウントする)。 例えば、/apple(,)\sorange\1/ は "apple, orange, cherry, peach" の 'apple, orange,' にマッチする。
\0NUL 文字にマッチする。この後ろに他の数字を続けてはならない。
\xhhhh(2 桁の 16 進数)というコードを持つ文字にマッチする。
\uhhhhhhhh(4 桁の 16 進数)というコードを持つ文字にマッチする。
- -

表 4.1正規表現における特殊文字

- -

括弧の使用

- -

正規表現パターンの一部分を括弧で囲むことで、マッチした部分文字列のその部分を記憶しておくことができます。一度記憶すると、後からその部分文字列を呼び戻すことができます。これに関しては 括弧で囲まれた部分文字列のマッチの使用 で説明しています。

- -

例えば、/Chapter (\d+)\.\d*/ というパターンでは、エスケープされた文字と特殊文字の部分がその例で、その部分を記憶するように指示しています。これは 'Chapter ' という文字列、それに続く 1 文字以上の数字(\d はいずれかの数字を意味し、+ は 1 回以上の繰り返しを意味する)、それに続く小数点(それ自体は特殊文字であり、小数点の前の \ はパターンが '.' という文字そのものを探すようにすることを意味する)、それに続く 0 文字以上の数字(\d は数字を意味し、* は 0 回以上の繰り返しを意味する)にマッチします。さらに、括弧を使うことで最初のマッチした数値を記憶させます。

- -

このパターンは "Open Chapter 4.3, paragraph 6" という文字列で見つかり、'4' が記憶されます。このパターンは "Chapter 3 and 4" では見つかりません。この文字列は '3' の後ろにピリオドがないためです。

- -

マッチした部分を記憶させることなく部分文字列にマッチさせたい場合は、その括弧においてパターンの前に ?: を付けてください。例えば、(?:\d+) は 1 文字以上の数字にマッチしますが、マッチした文字は記憶されません。

- -

{{ PreviousNext("JavaScript/Guide/Creating_a_Regular_Expression", "JavaScript/Guide/Working_with_Regular_Expressions") }}

diff --git a/files/ja/web/javascript/introduction_to_object-oriented_javascript/index.html b/files/ja/web/javascript/introduction_to_object-oriented_javascript/index.html deleted file mode 100644 index cbe9e10a0a..0000000000 --- a/files/ja/web/javascript/introduction_to_object-oriented_javascript/index.html +++ /dev/null @@ -1,381 +0,0 @@ ---- -title: オブジェクト指向 JavaScript 入門 -slug: Web/JavaScript/Introduction_to_Object-Oriented_JavaScript -tags: - - Constructor - - Encapsulation - - Inheritance - - Intermediate - - JavaScript - - Members - - Namespace - - OOP - - Object - - Object-Oriented -translation_of: Learn/JavaScript/Objects -translation_of_original: Web/JavaScript/Introduction_to_Object-Oriented_JavaScript ---- -
{{jsSidebar("Introductory")}}
- -

オブジェクト指向を追求することで、JavaScript は強力かつ柔軟な{{Glossary("OOP", "オブジェクト指向プログラミング")}}能力を特色としています。この記事ではまずオブジェクト指向プログラミングの入門から始め、JavaScript のオブジェクトモデルの復習、そして最後に JavaScript のオブジェクト指向プログラミングの概念を説明します。

- -

JavaScript の復習

- -

変数、型、関数、スコープといった JavaScript の概念について自信がないのでしたら、JavaScript「再」入門で該当するトピックをご覧いただくとよいでしょう。また、JavaScript ガイドもご覧ください。

- -

オブジェクト指向プログラミング

- -

オブジェクト指向プログラミング (OOP) は、実世界を元にしたモデルの作成に{{glossary("abstraction", "抽象化")}}を使用する、プログラミングのパラダイムです。OOP は{{glossary("modularity", "モジュラリティ")}}、{{glossary("polymorphism", "ポリモーフィズム")}}、{{glossary("encapsulation", "カプセル化")}}といった、これまでに確立されたパラダイム由来の技術を複数使用しています。今日、人気がある多くのプログラミング言語 (Java、JavaScript、C#、C++、Python、PHP、Ruby、Objective-C など) が OOP をサポートしています。

- -

OOP はソフトウェアを関数の集まりや単なるコマンドのリスト(これまでの伝統的な見方)としてではなく、協調して動作するオブジェクトの集まりであると考えます。OOP では、各々のオブジェクトがメッセージを受信し、データを処理し、また他のオブジェクトへメッセージを送信できます。各々のオブジェクトは明確な役割や責任を持つ、独立した小さな機械であると見なせます。

- -

OOP はプログラミングにおける柔軟性や保守性の向上を促し、大規模ソフトウェアエンジニアリングにおいて広く普及しています。OOP はモジュラリティを強く重視しているため、オブジェクト指向によるコードは開発をシンプルにします。また、コードを後から理解することが容易になります。オブジェクト指向によるコードはモジュラリティが低いプログラミング方法よりも、直接的な分析、コーディング、複雑な状況や手続きの理解を促進します。1

- -

用語集

- -
-
{{Glossary("Namespace", "ネームスペース")}} (名前空間)
-
開発者があらゆる機能をアプリケーション固有の一意な名前にまとめることができる一種の容器のことです。
-
{{Glossary("Class", "クラス")}}
-
オブジェクトの特性を定義するものです。クラスは、オブジェクトのプロパティやメソッドを定義するテンプレートです。
-
{{Glossary("Object", "オブジェクト")}}
-
クラスの実体です。
-
{{Glossary("Property", "プロパティ")}}
-
「色」などといったオブジェクトの特性です。
-
{{Glossary("Method", "メソッド")}}
-
「歩く」などといった、オブジェクトの能力です。これは、クラスに関連付けられたサブルーチンや関数です。
-
{{Glossary("Constructor", "コンストラクタ")}}
-
インスタンス化するときに呼び出されるメソッドです。コンストラクタの名前は通常、クラスの名前と同じです。
-
{{Glossary("Inheritance", "継承")}}
-
あるクラスが別のクラスから特性を引き継ぐことを指します。
-
{{Glossary("Encapsulation", "カプセル化")}}
-
データと、そのデータを使用するメソッドとをまとめる手法のことです。
-
{{Glossary("Abstraction", "抽象化")}}
-
実世界のモデルが、オブジェクトの複雑な継承、メソッド、プロパティの集合体によって適切に再現されている状態を指します。
-
{{Glossary("Polymorphism", "ポリモーフィズム")}}
-
Poly は "many"、morphism は "forms" を意味します。別々のクラスが同じメソッドやプロパティを定義可能であることを表します。
-
- -

オブジェクト指向プログラミングのより広範な説明については、Wikipedia の {{interwiki("wikipedia", "オブジェクト指向プログラミング")}} をご覧ください。

- -

プロトタイプベースプログラミング

- -

プロトタイプベースのプログラミングはクラスを使用せず、既存のプロトタイプオブジェクトをデコレート(あるいは拡張)してそのオブジェクトの持つ挙動を再利用する(クラスベースの言語における継承と同等)ことで実現される OOP モデルです(クラスレス、プロトタイプ指向、あるいはインスタンスベースプログラミングとも呼ばれます)。

- -

プロトタイプベース言語として先駆けの(そしてもっとも正統な)代表例は、David Ungar 氏と Randall Smith 氏によって開発された {{interwiki("wikipedia", "Self")}} です。とはいえ、クラスレスのプログラミングスタイルは最近ますます人気が高まり、JavaScript、Cecil、NewtonScript、Io、MOO、REBOL、Kevo、Squeak (ソフトウェア Morphic のコンポーネント操作の際の Viewer フレームワークとして使われています)などのプログラミング言語に採用されました。

- -

JavaScript のオブジェクト指向プログラミング

- -

ネームスペース

- -

ネームスペース(名前空間)とは、開発者が一意なアプリケーション固有の名前を付けて、機能をまとめることができる一種の容器です。JavaScript では、ネームスペースはメソッド、プロパティ、オブジェクトを包含する別のオブジェクトとなります。

- -

{{note('JavaScript では通常のオブジェクトとネームスペースとの間に、言語レベルの違いがない点に留意することが重要です。これは他の多くのオブジェクト指向言語とは異なっており、新たな JavaScript プログラマを混乱させることがあります。')}}

- -

JavaScript でネームスペースを作成する考え方はシンプルです。グローバルオブジェクトをひとつ作成して、すべての変数、メソッド、関数をそのオブジェクトのプロパティとすればよいのです。ネームスペースを使用すると、アプリケーション内で名前が衝突する可能性が低下します。これは各アプリケーションのオブジェクトが、アプリケーションで定義したグローバルオブジェクトのプロパティとなるからです。

- -

MYAPP という名前のグローバルオブジェクトを作成しましょう :

- -
// グローバルネームスペース
-var MYAPP = MYAPP || {};
- -

上記のサンプルコードでは、始めに MYAPP が(同じファイルまたは別のファイルで)すでに定義されているかを確認します。定義されている場合は、既存の MYAPP グローバルオブジェクトを使用します。定義されていない場合はメソッド、関数、変数、オブジェクトをカプセル化する、MYAPP という名前の空のオブジェクトを作成します。

- -

サブネームスペースも作成できます(グローバルオブジェクトを最初に定義する必要があることに注意):

- -
// サブネームスペース
-MYAPP.event = {};
- -

ネームスペースを作成して変数、関数、メソッドを追加する構文は以下のようになります :

- -
// 共通のメソッドやプロパティ向けに MYAPP.commonMethod という名前のコンテナを作成
-MYAPP.commonMethod = {
-  regExForName: "", // 名前を検証するための正規表現を定義
-  regExForPhone: "", // 電話番号を検証するための正規表現を定義
-  validateName: function(name){
-    // 名前に対してなんらかの処理を行う。"this.regExForName" を使用して
-    // 変数 regExForName にアクセス可能
-  },
-
-  validatePhoneNo: function(phoneNo){
-    // 電話番号に対してなんらかの処理を行う
-  }
-}
-
-// オブジェクトとともにメソッドを定義する
-MYAPP.event = {
-    addListener: function(el, type, fn) {
-    // 処理
-    },
-    removeListener: function(el, type, fn) {
-    // 処理
-    },
-    getEvent: function(e) {
-    // 処理
-    }
-
-    // 他のメソッドやプロパティを追加できる
-}
-
-// addListener メソッドを使用する構文:
-MYAPP.event.addListener("yourel", "type", callback);
- -

標準ビルトインオブジェクト

- -

JavaScript は、例えば MathObjectArrayString といったコアに組み込まれたオブジェクトがあります。以下の例では、乱数を取得するために Math オブジェクトの random() メソッドを使用する方法を示したものです。

- -
console.log(Math.random());
-
- -
註: この例、および以降の例では、{{domxref("console.log()")}} という名前の関数がグローバルで定義されていると仮定しています。実際は、console.log() 関数は JavaScript そのものの一部ではありませんが、多くのブラウザがデバッグ用に実装しています。
- -

JavaScript におけるコアオブジェクトの一覧については、JavaScript リファレンスの標準ビルトインオブジェクトをご覧ください。

- -

JavaScript ではすべてのオブジェクトが Object オブジェクトのインスタンスであり、それゆえに Object の全プロパティおよび全メソッドを継承します。

- -

カスタムオブジェクト

- -

クラス

- -

JavaScript はプロトタイプベースの言語であり、C++ や Java でみられる class 文がありません。これは時に、class 文を持つ言語に慣れているプログラマを混乱させます。その代わりに、JavaScript ではクラスのコンストラクタとして関数を使用します。クラスの定義は、関数の定義と同じほど簡単です。以下の例では、空のコンストラクタを使って Person という名前の新たなクラスを定義しています。

- -
var Person = function () {};
-
- -

オブジェクト(クラスのインスタンス)

- -

obj オブジェクトの新たなインスタンスを生成するには new obj 文を使用し、その結果(obj 型を持つ)を、後からアクセスするための変数に代入します。

- -

前出の例で、Person という名前のクラスを定義しました。以下の例では、2 つのインスタンス(person1person2)を生成しています。

- -
var person1 = new Person();
-var person2 = new Person();
-
- -
註: 初期化されていないインスタンスを生成する、新たに追加されたインスタンス化方法については、 {{jsxref("Object.create()")}} をご覧ください。
- -

コンストラクタ

- -

コンストラクタは、インスタンス化の際(オブジェクトのインスタンスが生成されたとき)に呼び出されます。コンストラクタは、クラスのメソッドです。JavaScript では、関数がオブジェクトのコンストラクタとして働きます。したがって、コンストラクタメソッドを明示的に定義する必要はありません。クラス内で定義されたすべてのアクションが、インスタンス化の際に実行されます。

- -

コンストラクタはオブジェクトのプロパティの設定や、オブジェクトの使用準備を行うメソッドの呼び出しを行うために使用されます。クラスのメソッドの追加やメソッドの定義は別の構文を使用して行うことについては、後ほど説明します。

- -

以下の例では Person をインスタンス化する際に、コンストラクタがメッセージをログに出力します。

- -
var Person = function () {
-  console.log('instance created');
-};
-
-var person1 = new Person();
-var person2 = new Person();
-
- -

プロパティ(オブジェクトの属性)

- -

プロパティは、クラス内にある変数です。オブジェクトのインスタンスはすべて、それらのプロパティを持ちます。プロパティがそれぞれのインスタンスで作成されるように、プロパティはコンストラクタ(関数)内で設定されます。

- -

カレントオブジェクトを示す this キーワードを使用して、クラス内でプロパティを扱うことができます。クラス外からプロパティにアクセス(読み取りや書き込み)するには、InstanceName.Property という構文を使用します。これは C++、Java、その他の言語と同じ構文です(クラスの内部では、プロパティの値の取得や設定に this.Property 構文を使用します)。

- -

以下の例では、Person クラスをインスタンス化する際に firstName プロパティを定義しています:

- -
var Person = function (firstName) {
-  this.firstName = firstName;
-  console.log('Person instantiated');
-};
-
-var person1 = new Person('Alice');
-var person2 = new Person('Bob');
-
-// オブジェクトの firstName プロパティを表示する
-console.log('person1 is ' + person1.firstName); // "person1 is Alice" と出力
-console.log('person2 is ' + person2.firstName); // "person2 is Bob" と出力
-
- -

メソッド

- -

メソッドは関数です(また、関数と同じように定義されます)が、他はプロパティと同じ考え方に従います。メソッドの呼び出しはプロパティへのアクセスと似ていますが、メソッド名の終わりに () を付加して、引数を伴うことがあります。メソッドを定義するには、クラスの prototype プロパティの名前付きプロパティに、関数を代入します。関数を代入した名前を使用して、オブジェクトのメソッドを呼び出すことができます。

- -

以下の例では、Person クラスで sayHello() メソッドを定義および使用しています。

- -
var Person = function (firstName) {
-  this.firstName = firstName;
-};
-
-Person.prototype.sayHello = function() {
-  console.log("Hello, I'm " + this.firstName);
-};
-
-var person1 = new Person("Alice");
-var person2 = new Person("Bob");
-
-// Person の sayHello メソッドを呼び出す
-person1.sayHello(); // "Hello, I'm Alice" と出力
-person2.sayHello(); // "Hello, I'm Bob" と出力
-
- -

JavaScript のメソッドはオブジェクトにプロパティとして割り付けられた通常の関数であり、「状況に関係なく」呼び出せます。以下のサンプルコードについて考えてみましょう:

- -
var Person = function (firstName) {
-  this.firstName = firstName;
-};
-
-Person.prototype.sayHello = function() {
-  console.log("Hello, I'm " + this.firstName);
-};
-
-var person1 = new Person("Alice");
-var person2 = new Person("Bob");
-var helloFunction = person1.sayHello;
-
-// "Hello, I'm Alice" と出力
-person1.sayHello();
-
-// "Hello, I'm Bob" と出力
-person2.sayHello();
-
-// "Hello, I'm undefined" と出力
-// (strict モードでは TypeError で失敗する)
-helloFunction();
-
-// true と出力
-console.log(helloFunction === person1.sayHello);
-
-// true と出力
-console.log(helloFunction === Person.prototype.sayHello);
-
-// "Hello, I'm Alice" と出力
-helloFunction.call(person1);
- -

この例で示すように、sayHello 関数を参照しているもの(person1Person.prototypehelloFunction 変数など)すべてが、同一の関数を示しています。関数を呼び出しているときの this の値は、関数の呼び出し方に依存します。もっとも一般的な、オブジェクトのプロパティから関数にアクセスする形式 (person1.sayHello()) で this を呼び出すときは、その関数を持つオブジェクト (person1) を this に設定します。これが、person1.sayHello() で名前として "Alice"、person2.sayHello() で名前として "Bob" が使用される理由です。一方、他の方法で呼び出す場合は this に設定されるものが変わります。変数 (helloFunction()) から this を呼び出すと、グローバルオブジェクト(ブラウザでは window)を this に設定します。このオブジェクトは(おそらく)firstName プロパティを持っていないため、"Hello, I'm undefined" になります(これは loose モードの場合です。strict モードでは異なる結果(エラー)になりますが、ここでは混乱を避けるために詳細は割愛します)。あるいは、例の最後で示したように Function#call (または Function#apply)を使用して、this を明示的に設定できます。

- -
註: this について、詳しくは {{jsxref("Global_Objects/Function/call","Function#call")}} および {{jsxref("Global_Objects/Function/apply","Function#apply")}} をご覧ください。
- -

継承

- -

継承は、1 つ以上のクラスを特化したバージョンとしてクラスを作成する方法です(JavaScript は単一継承のみサポートしています)。特化したクラスは一般的にと呼ばれ、またそれ以外のクラスは一般的にと呼ばれます。JavaScript では親クラスのインスタンスを子クラスに代入して、特化させることにより継承を行います。現代のブラウザでは、継承の実装に {{jsxref("Global_Objects/Object/create","Object.create","#Classical_inheritance_with_Object.create()")}} を使用することもできます。

- -
-

註: JavaScript は子クラスの prototype.constructor({{jsxref("Global_Objects/Object/prototype","Object.prototype")}} をご覧ください)を検出しないため、手動で明示しなければなりません。Stackoverflow に投稿された質問 "Why is it necessary to set the prototype constructor?" をご覧ください。

-
- -

以下の例では、Person の子クラスとして Student クラスを定義しています。そして、sayHello() メソッドの再定義と sayGoodBye() メソッドの追加を行っています。

- -
// Person コンストラクタを定義する
-var Person = function(firstName) {
-  this.firstName = firstName;
-};
-
-// Person.prototype にメソッドを 2 つ追加する
-Person.prototype.walk = function(){
-  console.log("I am walking!");
-};
-
-Person.prototype.sayHello = function(){
-  console.log("Hello, I'm " + this.firstName);
-};
-
-// Student コンストラクタを定義する
-function Student(firstName, subject) {
-  // 親のコンストラクタを呼び出す。呼び出しの際に "this" が
-  // 適切に設定されるようにする (Function#call を使用)
-  Person.call(this, firstName);
-
-  // Student 固有のプロパティを初期化する
-  this.subject = subject;
-};
-
-// Person.prototype を継承する、Student.prototype オブジェクトを作成する
-// 註: ここでよくある間違いが、Student.prototype を生成するために
-// "new Person()" を使用することです。これは様々な理由で間違っていますが、
-// まずこれでは Person の "firstName" 引数に渡すものがありません。
-// Person を呼び出す正しい場所はこれより前の、
-// Student から呼び出します。
-Student.prototype = Object.create(Person.prototype); // 以下の注釈を参照
-
-// "constructor" プロパティが Student を指すように設定する
-Student.prototype.constructor = Student;
-
-// "sayHello" メソッドを置き換える
-Student.prototype.sayHello = function(){
-  console.log("Hello, I'm " + this.firstName + ". I'm studying "
-              + this.subject + ".");
-};
-
-// "sayGoodBye" メソッドを追加する
-Student.prototype.sayGoodBye = function(){
-  console.log("Goodbye!");
-};
-
-// 使用例:
-var student1 = new Student("Janet", "Applied Physics");
-student1.sayHello();   // "Hello, I'm Janet. I'm studying Applied Physics."
-student1.walk();       // "I am walking!"
-student1.sayGoodBye(); // "Goodbye!"
-
-// instanceof が正常に機能するかをチェック
-console.log(student1 instanceof Person);  // true
-console.log(student1 instanceof Student); // true
-
- -

Student.prototype = Object.create(Person.prototype); という行について :
- {{jsxref("Global_Objects/Object/create","Object.create")}} が存在しない古い JavaScript エンジンでは、「{{原語併記("ポリフィル","polyfill")}}」 ("shim" とも呼ばれます。リンク先の記事をご覧ください)または同様の結果になる以下のような関数を使用できます。:

- -
function createObject(proto) {
-    function ctor() { }
-    ctor.prototype = proto;
-    return new ctor();
-}
-
-// 使用法:
-Student.prototype = createObject(Person.prototype);
-
- -
註: Object.create や古いエンジン向けの shim が何を行っているかについては、{{jsxref("Global_Objects/Object/create","Object.create")}} をご覧ください。
- -

オブジェクトをインスタンス化する方法を問わずに、this の参照先を適切に指定するのは時に難しいものです。ですが、これを容易にするシンプルなイディオムがあります。

- -
var Person = function(firstName) {
-  if (this instanceof Person) {
-    this.firstName = firstName;
-  } else {
-    return new Person(firstName);
-  }
-}
-
- -

カプセル化

- -

前の例では、Person クラスによる walk() メソッドの実装状況を Student が知らなくても、そのメソッドを使用できました。Student クラスは変更の必要がない限り、そのメソッドを明示的に定義する必要はありません。すべてのクラスのデータとメソッドがひとつのユニットに収められていることから、これをカプセル化と呼びます。

- -

情報を隠蔽することは、他の言語でも private または protected なメソッドやプロパティという形で一般的な機能です。JavaScript でも同様のことをシミュレートできますが、オブジェクト指向プログラミングに必須というわけではありません。2

- -

抽象化

- -

抽象化は、取り組んでいる問題の箇所を継承(特殊化)や合成によってモデル化することを可能にする仕組みです。JavaScript では継承によって特殊化を、クラスのインスタンスを別のオブジェクトの属性値にすることで合成を実現しています。

- -

JavaScript の Function クラスは Object クラスから継承しています(これはモデルを特殊化している一例です)。また、Function.prototype プロパティは Object のインスタンスです (これは合成の一例です)。

- -
var foo = function () {};
-
-// "foo is a Function: true" と出力
-console.log('foo is a Function: ' + (foo instanceof Function));
-
-// "foo.prototype is an Object: true" と出力
-console.log('foo.prototype is an Object: ' + (foo.prototype instanceof Object));
- -

ポリモーフィズム

- -

すべてのメソッドやプロパティが prototype プロパティの内部で実装されているのと同じように、異なるクラスで同じ名前のメソッドを定義できます。メソッドは 2 つのクラスに親子関係(すなわち、あるクラスが別のクラスから継承されている)がない限り、自身が定義されたクラスに収められます。

- -

注記

- -

これらは JavaScript でオブジェクト指向プログラミングを実装する唯一の方法ではありません。この点で JavaScript はとても融通がききます。同様に、ここで示した技術は言語ハックをまったくしていませんし、他言語のオブジェクト理論における実装を模倣してもいません。

- -

このほかにも、JavaScript によるより高度なオブジェクト指向プログラミングのテクニックがありますが、この入門記事で扱う範囲を超えます。

- -

参考情報

- -
    -
  1. Wikipedia: "Object-oriented programming" (日本語版)
  2. -
  3. Wikipedia: "Encapsulation (object-oriented programming)" (日本語版)
  4. -
diff --git a/files/ja/web/javascript/introduction_to_using_xpath_in_javascript/index.html b/files/ja/web/javascript/introduction_to_using_xpath_in_javascript/index.html deleted file mode 100644 index 8d63ce70da..0000000000 --- a/files/ja/web/javascript/introduction_to_using_xpath_in_javascript/index.html +++ /dev/null @@ -1,411 +0,0 @@ ---- -title: JavaScript で XPath を使用する -slug: Web/JavaScript/Introduction_to_using_XPath_in_JavaScript -translation_of: Web/XPath/Introduction_to_using_XPath_in_JavaScript ---- -

このドキュメントでは、JavaScript の内部、拡張機能、そして Web サイトから XPath を使用するためのインターフェイスについて説明します。Mozilla は DOM 3 XPath をかなりの量実装しており、XPath 式は HTML と XML ドキュメントの両方に対して実行できます。

- -

XPath を使用するための主なインターフェースは、Document オブジェクトの evaluate 関数です。

- -

document.evaluate

- -

このメソッドは、XML ベースのドキュメント (HTML ドキュメントを含む) に対して XPath 式を評価し、XPathResult オブジェクトを返します。このメソッドの既存のドキュメントは document.evaluate にありますが、今のところ我々が必要としているものには乏しいです。

- -
var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );
-
- -

Parameters

- -

evaluate 関数は合計5つのパラメータを取ります。

- - - -

Return Value

- -

resultType パラメータで指定された型の XPathResult オブジェクトを返します。XPathResult インターフェースはここで定義されています。

- -

Implementing a Default Namespace Resolver

- -

document オブジェクトの createNSResolver メソッドを使用して名前空間リゾルバを作成します。

- -
var nsResolver = document.createNSResolver( contextNode.ownerDocument == null ? contextNode.documentElement : contextNode.ownerDocument.documentElement );
-
- -

Or alternatively by using the <code>createNSResolver</code> method of a <code>XPathEvaluator</code> object. <pre> var xpEvaluator = new XPathEvaluator(); var nsResolver = xpEvaluator.createNSResolver( contextNode.ownerDocument == null ? contextNode.documentElement : contextNode.ownerDocument.documentElement ); </pre> そして、namespaceResolver パラメータとして nsResolver 変数である document.evaluate を渡します。

- -

注意: XPath は、ヌル名前空間の要素にのみマッチするように、接頭辞のない QNames を定義しています。XPath では、通常の要素参照 (例: xmlns='http://www.w3.org/1999/xhtml'p[@id='_myid']) に適用されるデフォルトの名前空間を拾う方法はありません。NULL ではない名前空間のデフォルト要素にマッチさせるには、['namespace-uri()='http://www.w3.org/1999/xhtml' and name()='p' and @id='_myid'] のような形式を使用して特定の要素を参照する必要があります (このアプローチは、名前空間がわからない動的な XPath の場合にうまく機能します)。後者の方法を取りたい場合は、ユーザ定義の名前空間リゾルバを作成する方法を参照してください。

- -

Notes

- -

任意の DOM ノードを名前空間を解決するように適応させ、 XPath 式をドキュメント内で出現したノードのコンテキストからの相対評価を簡単に行えるようにします。このアダプタは、ノード上の DOM Level 3 メソッド lookupNamespaceURI と同様に動作し、 lookupNamespaceURI が呼び出された時点でのノードの階層内で利用可能な現在の情報を使用して、指定したプレフィックスから namespaceURI を解決します。また、暗黙の xml 接頭辞も正しく解決します。

- -

Specifying the Return Type

- -

The returned variable xpathResult from document.evaluate can either be composed of individual nodes (simple types), or a collection of nodes (node-set types).

- -

Simple Types

- -

resultType に希望する結果タイプがどちらかに指定されている場合。

- - - -

XPathResult オブジェクトの以下のプロパティにそれぞれアクセスして、式の戻り値を取得します。

- - - -
Example
- -

The following uses the XPath expression count(//p) to obtain the number of <p> elements in an HTML document:

- -
var paragraphCount = document.evaluate( 'count(//p)', document, null, XPathResult.ANY_TYPE, null );
-
-alert( 'This document contains ' + paragraphCount.numberValue + ' paragraph elements' );
-
- -

Although JavaScript allows us to convert the number to a string for display, the XPath interface will not automatically convert the numerical result if the stringValue property is requested, so the following code will not work:

- -
var paragraphCount = document.evaluate('count(//p)', document, null, XPathResult.ANY_TYPE, null );
-
-alert( 'This document contains ' + paragraphCount.stringValue + ' paragraph elements' );
-
- -

Instead, it will return an exception with the code NS_DOM_TYPE_ERROR.

- -

Node-Set Types

- -

The XPathResult object allows node-sets to be returned in 3 principal different types:

- - - -
Iterators
- -

When the specified result type in the resultType parameter is either:

- - - -

The XPathResult object returned is a node-set of matched nodes which will behave as an iterator, allowing us to access the individual nodes contained by using the iterateNext() method of the XPathResult.

- -

Once we have iterated over all of the individual matched nodes, iterateNext() will return null.

- -

Note however, that if the document is mutated (the document tree is modified) between iterations that will invalidate the iteration and the invalidIteratorState property of XPathResult is set to true, and a NS_ERROR_DOM_INVALID_STATE_ERR exception is thrown.

- -
Iterator Example
- -
var iterator = document.evaluate('//phoneNumber', documentNode, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null );
-
-try {
-  var thisNode = iterator.iterateNext();
-
-  while (thisNode) {
-    alert( thisNode.textContent );
-    thisNode = iterator.iterateNext();
-  }
-}
-catch (e) {
-  alert( 'Error: Document tree modified during iteration ' + e );
-}
-
- -
Snapshots
- -

When the specified result type in the resultType parameter is either:

- - - -

The XPathResult object returned is a static node-set of matched nodes, which allows us to access each node through the snapshotItem(itemNumber) method of the XPathResult object, where itemNumber is the index of the node to be retrieved. The total number of nodes contained can be accessed through the snapshotLength property.

- -

Snapshots do not change with document mutations, so unlike the iterators, the snapshot does not become invalid, but it may not correspond to the current document, for example, the nodes may have been moved, it might contain nodes that no longer exist, or new nodes could have been added.

- -
Snapshot Example
- -
var nodesSnapshot = document.evaluate('//phoneNumber', documentNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
-
-for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )
-{
-  alert( nodesSnapshot.snapshotItem(i).textContent );
-}
-
- -
First Node
- -

When the specified result type in the resultType parameter is either:

- - - -

The XPathResult object returned is only the first found node that matched the XPath expression. This can be accessed through the singleNodeValue property of the XPathResult object. This will be null if the node set is empty.

- -

Note that, for the unordered subtype the single node returned might not be the first in document order, but for the ordered subtype you are guaranteed to get the first matched node in the document order.

- -
First Node Example
- -
var firstPhoneNumber = document.evaluate('//phoneNumber', documentNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null );
-
-alert( 'The first phone number found is ' + firstPhoneNumber.singleNodeValue.textContent );
-
- -

The ANY_TYPE Constant

- -

When the result type in the resultType parameter is specified as ANY_TYPE, the XPathResult object returned, will be whatever type that naturally results from the evaluation of the expression.

- -

It could be any of the simple types (NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE), but, if the returned result type is a node-set then it will only be an UNORDERED_NODE_ITERATOR_TYPE.

- -

To determine that type after evaluation, we use the resultType property of the XPathResult object. The constant values of this property are defined in the appendix. None Yet =====Any_Type Example===== <pre> </pre>

- -

Examples

- -

Within an HTML Document

- -

The following code is intended to be placed in any JavaScript fragment within or linked to the HTML document against which the XPath expression is to be evaluated.

- -

To extract all the <h2> heading elements in an HTML document using XPath, the xpathExpression is simply '//h2'. Where, // is the Recursive Descent Operator that matches elements with the nodeName h2 anywhere in the document tree. The full code for this is: link to introductory xpath doc

- -
var headings = document.evaluate('//h2', document, null, XPathResult.ANY_TYPE, null );
-
- -

Notice that, since HTML does not have namespaces, we have passed null for the namespaceResolver parameter.

- -

Since we wish to search over the entire document for the headings, we have used the document object itself as the contextNode.

- -

The result of this expression is an XPathResult object. If we wish to know the type of result returned, we may evaluate the resultType property of the returned object. In this case, that will evaluate to 4, an UNORDERED_NODE_ITERATOR_TYPE. This is the default return type when the result of the XPath expression is a node set. It provides access to a single node at a time and may not return nodes in a particular order. To access the returned nodes, we use the iterateNext() method of the returned object:

- -
var thisHeading = headings.iterateNext();
-
-var alertText = 'Level 2 headings in this document are:\n'
-
-while (thisHeading) {
-  alertText += thisHeading.textContent + '\n';
-  thisHeading = headings.iterateNext();
-}
-
- -

Once we iterate to a node, we have access to all the standard DOM interfaces on that node. After iterating through all the h2 elements returned from our expression, any further calls to iterateNext() will return null.

- -

Evaluating against an XML document within an Extension

- -

The following uses an XML document located at chrome://yourextension/content/peopleDB.xml as an example.

- -
<?xml version="1.0"?>
-<people xmlns:xul = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" >
-  <person>
-	<name first="george" last="bush" />
-	<address street="1600 pennsylvania avenue" city="washington" country="usa"/>
-	<phoneNumber>202-456-1111</phoneNumber>
-  </person>
-  <person>
-	<name first="tony" last="blair" />
-	<address street="10 downing street" city="london" country="uk"/>
-	<phoneNumber>020 7925 0918</phoneNumber>
-  </person>
-</people>
-
- -

To make the contents of the XML document available within the extension, we create an XMLHttpRequest object to load the document synchronously, the variable xmlDoc will contain the document as an XMLDocument object against which we can use the evaluate method

- -

JavaScript used in the extensions xul/js documents.

- -
var req = new XMLHttpRequest();
-
-req.open("GET", "chrome://yourextension/content/peopleDB.xml", false);
-req.send(null);
-
-var xmlDoc = req.responseXML;
-
-var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
-
-var personIterator = xmlDoc.evaluate('//person', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
-
- -

Note

- -

When the XPathResult object is not defined, the constants can be retrieved in privileged code using Components.interfaces.nsIDOMXPathResult.ANY_TYPE (CI.nsIDOMXPathResult). Similarly, an XPathEvaluator can be created using:

- -
Components.classes["@mozilla.org/dom/xpath-evaluator;1"].createInstance(Components.interfaces.nsIDOMXPathEvaluator)
- -

Appendix

- -

Implementing a User Defined Namespace Resolver

- -

This is an example for illustration only. This function will need to take namespace prefixes from the xpathExpression and return the URI that corresponds to that prefix. For example, the expression:

- -
'//xhtml:td/mathml:math'
-
- -

will select all MathML expressions that are the children of (X)HTML table data cell elements.

- -

In order to associate the 'mathml:' prefix with the namespace URI 'http://www.w3.org/1998/Math/MathML' and 'xhtml:' with the URI 'http://www.w3.org/1999/xhtml' we provide a function:

- -
function nsResolver(prefix) {
-  var ns = {
-    'xhtml' : 'http://www.w3.org/1999/xhtml',
-    'mathml': 'http://www.w3.org/1998/Math/MathML'
-  };
-  return ns[prefix] || null;
-}
-
- -

Our call to document.evaluate would then looks like:

- -
document.evaluate( '//xhtml:td/mathml:math', document, nsResolver, XPathResult.ANY_TYPE, null );
-
- -

Implementing a default namespace for XML documents

- -

As noted in the Implementing a Default Namespace Resolver previously, the default resolver does not handle the default namespace for XML documents. For example with this document:

- -
<?xml version="1.0" encoding="UTF-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
-    <entry />
-    <entry />
-    <entry />
-</feed>
-
- -

doc.evaluate('//entry', doc, nsResolver, XPathResult.ANY_TYPE, null) will return an empty set, where nsResolver is the resolver returned by createNSResolver. Passing a null resolver doesn't work any better, either.

- -

One possible workaround is to create a custom resolver that returns the correct default namespace (the Atom namespace in this case). Note that you still have to use some namespace prefix in your XPath expression, so that the resolver function will be able to change it to your required namespace. E.g.:

- -
function resolver() {
-    return 'http://www.w3.org/2005/Atom';
-}
-doc.evaluate('//myns:entry', doc, resolver, XPathResult.ANY_TYPE, null)
-
- -

Note that a more complex resolver will be required if the document uses multiple namespaces.

- -

An approach which might work better (and allow namespaces not to be known ahead of time) is described in the next section.

- -

Using XPath functions to reference elements with a default namespace

- -

Another approach to match default elements in a non-null namespace (and one which works well for dynamic XPath expressions where the namespaces might not be known), involves referring to a particular element using a form such as [namespace-uri()='http://www.w3.org/1999/xhtml' and name()='p' and @id='_myid']. This circumvents the problem of an XPath query not being able to detect the default namespace on a regularly labeled element.

- -

Getting specifically namespaced elements and attributes regardless of prefix

- -

If one wishes to provide flexibility in namespaces (as they are intended) by not necessarily requiring a particular prefix to be used when finding a namespaced element or attribute, one must use special techniques.

- -

While one can adapt the approach in the above section to test for namespaced elements regardless of the prefix chosen (using local-name() in combination with namespace-uri() instead of name()), a more challenging situation occurs, however, if one wishes to grab an element with a particular namespaced attribute in a predicate (given the absence of implementation-independent variables in XPath 1.0).

- -

For example, one might try (incorrectly) to grab an element with a namespaced attribute as follows: var xpathlink = someElements[local-name(@*)="href" and namespace-uri(@*)='http://www.w3.org/1999/xlink'];

- -

This could inadvertently grab some elements if one of its attributes existed that had a local name of "href", but it was a different attribute which had the targeted (XLink) namespace (instead of @href).

- -

In order to accurately grab elements with the XLink @href attribute (without also being confined to predefined prefixes in a namespace resolver), one could obtain them as follows:

- -
var xpathEls = 'someElements[@*[local-name() = "href" and namespace-uri() = "http://www.w3.org/1999/xlink"]]'; // Grabs elements with any single attribute that has both the local name 'href' and the XLink namespace
-var thislevel = xml.evaluate(xpathEls, xml, null, XPathResult.ANY_TYPE, null);
-var thisitemEl = thislevel.iterateNext();
-
- -

XPathResult Defined Constants

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Result Type Defined ConstantValueDescription
ANY_TYPE0A result set containing whatever type naturally results from the evaluation of the expression. Note that if the result is a node-set then UNORDERED_NODE_ITERATOR_TYPE is always the resulting type.
NUMBER_TYPE1A result containing a single number. This is useful for example, in an XPath expression using the count() function.
STRING_TYPE2A result containing a single string.
BOOLEAN_TYPE3A result containing a single boolean value. This is useful for example, in an XPath expression using the not() function.
UNORDERED_NODE_ITERATOR_TYPE4A result node-set containing all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the document.
ORDERED_NODE_ITERATOR_TYPE5A result node-set containing all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document.
UNORDERED_NODE_SNAPSHOT_TYPE6A result node-set containing snapshots of all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the document.
ORDERED_NODE_SNAPSHOT_TYPE7A result node-set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document.
ANY_UNORDERED_NODE_TYPE8A result node-set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression.
FIRST_ORDERED_NODE_TYPE9A result node-set containing the first node in the document that matches the expression.
- -

See also

- - - -
-

Original Document Information

- - -
diff --git a/files/ja/web/javascript/reference/global_objects/array/index/index.html b/files/ja/web/javascript/reference/global_objects/array/index/index.html deleted file mode 100644 index 1d2e7a4797..0000000000 --- a/files/ja/web/javascript/reference/global_objects/array/index/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: index -slug: Web/JavaScript/Reference/Global_Objects/Array/index ---- -

概要

-

正規表現マッチにより作成された配列において、文字列中での一致部分の、0 から始まるインデックス。

- - - - - - - - - - - - - - - -
Array のプロパティ
静的
実装されたバージョンJavaScript 1.2
diff --git a/files/ja/web/javascript/reference/global_objects/array/input/index.html b/files/ja/web/javascript/reference/global_objects/array/input/index.html deleted file mode 100644 index 166ed28656..0000000000 --- a/files/ja/web/javascript/reference/global_objects/array/input/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: input -slug: Web/JavaScript/Reference/Global_Objects/Array/input ---- -

-

{{ 英語版章題("Summary") }} -

-

概要

-

正規表現マッチにより作成された配列において、正規表現がマッチを行った元の文字列を反映します。 -

- - - - - - - - - - - -
Array のプロパティ
静的
実装されたバージョン:JavaScript 1.2, NES 3.0
-
-
-{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Global_Objects/Array/input", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/input", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Array/input" } ) }} diff --git a/files/ja/web/javascript/reference/global_objects/array/prototype/index.html b/files/ja/web/javascript/reference/global_objects/array/prototype/index.html deleted file mode 100644 index dc20c31a41..0000000000 --- a/files/ja/web/javascript/reference/global_objects/array/prototype/index.html +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Array.prototype -slug: Web/JavaScript/Reference/Global_Objects/Array/prototype -tags: - - Array - - JavaScript - - Junk - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Array/prototype ---- -
{{JSRef}}
- -

解説

- -

{{jsxref("Array")}} インスタンスは、 Array.prototype を継承しています。すべてのコンストラクターと同様に、コンストラクターの prototype オブジェクトを変更して、すべての {{jsxref("Array")}} インスタンスを変更することができます。例えば、新しいメソッドやプロパティを追加して、すべての Array オブジェクトを拡張することができます。例えば、これは{{Glossary("Polyfill", "ポリフィル")}}に使用されます。

- -

ただし、配列オブジェクトに標準外メソッドを追加すると、後で独自のコードに問題が発生したり、 JavaScript への機能の追加の際に問題が発生することがあります。

- -

豆知識: Array.prototype はそれ自体が {{jsxref("Array")}} です。

- -
Array.isArray(Array.prototype); // true
-
- -

{{js_property_attributes(0, 0, 0)}}

- -

プロパティ

- -
-
Array.prototype.constructor
-
オブジェクトの prototype を生成する関数を指定します。
-
{{jsxref("Array.prototype.length")}}
-
配列内の要素数を反映します。
-
{{jsxref("Array.@@unscopables", "Array.prototype[@@unscopables]")}}
-
with バインディングのスコープから除外されるプロパティ名を保持するシンボル。
-
- -

メソッド

- -

Mutator メソッド

- -

これらのメソッドは、配列を書き換えます。

- -
-
{{jsxref("Array.prototype.copyWithin()")}}
-
配列内で配列内の連続した要素をコピーします。
-
{{jsxref("Array.prototype.fill()")}}
-
配列内の指定した開始位置から終了位置までの要素を固定値で埋めます。
-
{{jsxref("Array.prototype.pop()")}}
-
配列から最後の要素を取り除き、戻り値として返します。
-
{{jsxref("Array.prototype.push()")}}
-
配列の最後に 1 個以上の要素を追加し、新しい配列の長さを返します。
-
{{jsxref("Array.prototype.reverse()")}}
-
配列の要素の順番を逆転させます (最初の要素は最後に、最後の要素は最初になります)。
-
{{jsxref("Array.prototype.shift()")}}
-
配列から最初の要素を取り除き、その要素を返します。
-
{{jsxref("Array.prototype.sort()")}}
-
配列内で要素を整列し、配列を返します。
-
{{jsxref("Array.prototype.splice()")}}
-
配列に対して複数の要素を追加したり取り除いたりします。
-
{{jsxref("Array.prototype.unshift()")}}
-
配列の最初に 1 個以上の要素を追加し、配列の変更後の長さを返します。
-
- -

アクセサーメソッド

- -

これらのメソッドは呼び出し対象の配列を書き換えず、配列を何らかの形で表したものを返します。

- -
-
{{jsxref("Array.prototype.concat()")}}
-
この配列に他の配列や値を結合して新しい配列を返します。
-
{{jsxref("Array.prototype.includes()")}}
-
この配列が特定の要素を含むかどうか判定し、その結果を true または false で返します。
-
{{jsxref("Array.prototype.indexOf()")}}
-
指定された値と等しい値を持つ最初の (添字の一番小さい) 要素の添字を返します。見つからない場合、-1 を返します。
-
{{jsxref("Array.prototype.join()")}}
-
配列のすべての要素を結合した文字列を返します。
-
{{jsxref("Array.prototype.lastIndexOf()")}}
-
指定された値と等しい値を持つ最後の (添字の一番大きい) 要素の添字を返します。見つからない場合、-1 を返します。
-
{{jsxref("Array.prototype.slice()")}}
-
配列の一部を取り出して新しい配列として返します。
-
{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}
-
指定された配列を表す配列リテラルを返します。この値を使って新しい配列を作れます。{{jsxref("Object.prototype.toSource()")}} メソッドを上書きしています。
-
{{jsxref("Array.prototype.toString()")}}
-
配列とその要素を表す文字列を返します。{{jsxref("Object.prototype.toString()")}} メソッドを上書きしています。
-
{{jsxref("Array.prototype.toLocaleString()")}}
-
配列とその要素を表すロケールに従った文字列を返します。{{jsxref("Object.prototype.toLocaleString()")}} メソッドを上書きしています。
-
- -

反復メソッド

- -

いくつかのメソッドは、配列を処理する際にコールバックされる関数を引数に取ります。これらのメソッドが呼ばれる時、配列の length 値を一時記憶するため、コールバック中にこの長さを超えて追加された要素にはアクセスしません。配列に対するその他の変更 (要素の値の書き換えや削除) は、変更された要素にメソッドが後でアクセスした場合の操作結果に影響を及ぼす可能性があります。そのような場合におけるこれらのメソッドの振る舞いは正確に定義されていますが、コードの読者を混乱させないよう、その振る舞いに依存すべきではありません。配列を変化させなければならない場合は、代わりに新しい配列にコピーしてください。

- -
-
{{jsxref("Array.prototype.entries()")}}
-
新しい Array Iterator オブジェクトを返します。このオブジェクトは、配列中の各インデックスに対する key/value ペアを保持しています。
-
{{jsxref("Array.prototype.every()")}}
-
指定したテスト関数を配列中のすべての要素が満たした場合に true を返します。
-
{{jsxref("Array.prototype.filter()")}}
-
指定したフィルタリング関数が true を返す、配列中の要素を格納した新しい配列を生成します。
-
{{jsxref("Array.prototype.find()")}}
-
指定したテスト関数を満たす、配列中の要素の値を返します。1 個も見つからない場合は undefined を返します。
-
{{jsxref("Array.prototype.findIndex()")}}
-
指定したテスト関数を満たす、配列中の要素のインデックスを返します。1 個も見つからない場合は -1 を返します。
-
{{jsxref("Array.prototype.forEach()")}}
-
配列中のそれぞれの要素について関数を呼び出します。
-
{{jsxref("Array.prototype.keys()")}}
-
新しい Array Iterator を返します。このオブジェクトは配列中の各インデックスのキーを保持します。
-
{{jsxref("Array.prototype.map()")}}
-
配列内のすべての要素に対して与えられた関数を呼び出し、その結果を格納した新しい配列を生成します。
-
{{jsxref("Array.prototype.reduce()")}}
-
アキュムレータと配列内のすべての要素に対して (左から右の順で) 関数を適用し、単一の値に還元します。
-
{{jsxref("Array.prototype.reduceRight()")}}
-
アキュムレータと配列内のすべての要素に対して (右から左の順で) 関数を適用し、単一の値に還元します。
-
{{jsxref("Array.prototype.some()")}}
-
指定したテスト関数を配列中の少なくとも 1 個の要素が満たした場合に true を返します。
-
{{jsxref("Array.prototype.values()")}}
-
新しい Array Iterator オブジェクトを返します。このオブジェクトは、配列中の各インデックスの値を保持します。
-
{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}}
-
新しい Array Iterator オブジェクトを返します。このオブジェクトは、配列中の各インデックスの値を保持します。
-
- -

ジェネリックメソッド (非標準)

- -

JavaScript の Array オブジェクト上の多くのメソッドは、配列型 (array-like) のあらゆるオブジェクトに対し広く適用されるよう設計されています。すなわち、どんなオブジェクトでも length プロパティを持ち、数値プロパティ名を使う (array[5] のような) アクセスが有効なら、それらを適用できます。{{jsxref("Array.join", "join")}} のような一部のメソッドは、呼び出し対象オブジェクトの length や数値プロパティを読み取るだけです。 一方、{{jsxref("Array.reverse", "reverse")}} のようなメソッドは、対象オブジェクトの数値プロパティや length が変更可能であることを要求するため、length プロパティや設定される合成数値プロパティの変更を許さない {{jsxref("String")}} のようなオブジェクトに対して呼び出すことができません。

- -

仕様書

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('ES1')}}{{Spec2('ES1')}}初回定義
{{SpecName('ES5.1', '#sec-15.4.3.1', 'Array.prototype')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype', 'Array.prototype')}}{{Spec2('ES6')}}copyWithin(), fill(), entries(), keys(), values(), find(), findIndex() メソッドを追加
{{SpecName('ES7', '#sec-array.prototype', 'Array.prototype')}}{{Spec2('ES7')}}includes() メソッドを追加
{{SpecName('ESDraft', '#sec-array.prototype', 'Array.prototype')}}{{Spec2('ESDraft')}}
- -

ブラウザーの対応

- - - -

{{Compat("javascript.builtins.Array.prototype")}}

- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/global_objects/asyncfunction/prototype/index.html b/files/ja/web/javascript/reference/global_objects/asyncfunction/prototype/index.html deleted file mode 100644 index 46bf817819..0000000000 --- a/files/ja/web/javascript/reference/global_objects/asyncfunction/prototype/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: AsyncFunction.prototype -slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype -tags: - - Experimental - - JavaScript - - Property - - Prototype - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype ---- -
{{JSRef}}
- -

AsyncFunction.prototype プロパティは、{{jsxref("AsyncFunction")}} プロトタイプオブジェクトを表します。

- -

説明

- -

{{jsxref("AsyncFunction")}} オブジェクトは、AsyncFunction.prototype を継承します。AsyncFunction.prototype は修正できません。

- -

プロパティ

- -
-
AsyncFunction.constructor
-
初期値は {{jsxref("AsyncFunction")}}。
-
AsyncFunction.prototype[@@toStringTag]
-
"AsyncFunction" を返す。
-
- -

仕様

- - - - - - - - - - - - - - - - -
仕様ステータスコメント
{{SpecName('Async Function', '#async-function-definitions', 'async function')}}{{Spec2('Async Function')}}提案
- -

ブラウザー実装状況

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
機能ChromeFirefox (Gecko)Internet Explorer EdgeOperaSafari (WebKit)
基本サポート{{CompatUnknown}}{{CompatGeckoDesktop("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
機能AndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基本サポート{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

関連項目

- - diff --git a/files/ja/web/javascript/reference/global_objects/atomics/notify/index.html b/files/ja/web/javascript/reference/global_objects/atomics/notify/index.html new file mode 100644 index 0000000000..be17a5f891 --- /dev/null +++ b/files/ja/web/javascript/reference/global_objects/atomics/notify/index.html @@ -0,0 +1,142 @@ +--- +title: Atomics.wake() +slug: Web/JavaScript/Reference/Global_Objects/Atomics/wake +translation_of: Web/JavaScript/Reference/Global_Objects/Atomics/notify +--- +
{{JSRef}} {{SeeCompatTable}}
+ +

静的メソッドである Atomics.wake() は待ち行列中のいくつかのエージェントを起こします。

+ +
+

付記:この操作は共有された {{jsxref("Int32Array")}} に対してのみ許可されています。

+
+ +

構文

+ +
Atomics.wake(typedArray, index, count)
+
+ +

引数

+ +
+
typedArray
+
共有された {{jsxref("Int32Array")}}。
+
index
+
起こす対象となる typedArray 中の位置。
+
count
+
起こすエージェントの数。既定値は {{jsxref("Infinity", "+Infinity")}} である。
+
+ +

返り値

+ +

起きたエージェントの数。

+ +

例外

+ + + +

+ +

共有された Int32Array を用意します:

+ +
var sab = new SharedArrayBuffer(1024);
+var int32 = new Int32Array(sab);
+
+ +

読み手のスレッドは、0 番目の値が 0 であることを期待してスリープします。それが満たされている間、この場合は 0 番目の値が 0 である間は処理が進みません。しかし書き手のスレッドが新しい値 (この場合は 123)をストアした場合、読み手のスレッドは読み手のスレッドによって起こされ、新しい値 (123)を取得します。

+ +
Atomics.wait(int32, 0, 0);
+console.log(int32[0]); // 123
+ +

書き手のスレッドは新しい値をストアし、待っているスレッドを起こします:

+ +
console.log(int32[0]); // 0;
+Atomics.store(int32, 0, 123);
+Atomics.wake(int32, 0, 1);
+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('Shared Memory', '#Atomics.wake', 'Atomics.wake')}}{{Spec2('Shared Memory')}}初期定義
+ +

ブラウザ互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}} [2]{{CompatNo}}{{CompatGeckoDesktop("46")}} [1] [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("46")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 設定で無効になっています。about:config で javascript.options.shared_memorytrue に設定することで利用できます。

+ +

[2] 現在実装中で、利用には次のオプションをつけて起動する必要があります:--js-flags=--harmony-sharedarraybuffer --enable-blink-feature=SharedArrayBuffer

+ +

[3] バージョン 46 と 47 では Atomics.futexWake() という名前で利用できます。また引数 count の既定値は 0 となっています。列の代わりに Atomics.OK、Atomics.TIMEDOUT、Atomics.NOTEQUAL を返します

+ +

関連情報

+ + diff --git a/files/ja/web/javascript/reference/global_objects/atomics/wake/index.html b/files/ja/web/javascript/reference/global_objects/atomics/wake/index.html deleted file mode 100644 index be17a5f891..0000000000 --- a/files/ja/web/javascript/reference/global_objects/atomics/wake/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Atomics.wake() -slug: Web/JavaScript/Reference/Global_Objects/Atomics/wake -translation_of: Web/JavaScript/Reference/Global_Objects/Atomics/notify ---- -
{{JSRef}} {{SeeCompatTable}}
- -

静的メソッドである Atomics.wake() は待ち行列中のいくつかのエージェントを起こします。

- -
-

付記:この操作は共有された {{jsxref("Int32Array")}} に対してのみ許可されています。

-
- -

構文

- -
Atomics.wake(typedArray, index, count)
-
- -

引数

- -
-
typedArray
-
共有された {{jsxref("Int32Array")}}。
-
index
-
起こす対象となる typedArray 中の位置。
-
count
-
起こすエージェントの数。既定値は {{jsxref("Infinity", "+Infinity")}} である。
-
- -

返り値

- -

起きたエージェントの数。

- -

例外

- - - -

- -

共有された Int32Array を用意します:

- -
var sab = new SharedArrayBuffer(1024);
-var int32 = new Int32Array(sab);
-
- -

読み手のスレッドは、0 番目の値が 0 であることを期待してスリープします。それが満たされている間、この場合は 0 番目の値が 0 である間は処理が進みません。しかし書き手のスレッドが新しい値 (この場合は 123)をストアした場合、読み手のスレッドは読み手のスレッドによって起こされ、新しい値 (123)を取得します。

- -
Atomics.wait(int32, 0, 0);
-console.log(int32[0]); // 123
- -

書き手のスレッドは新しい値をストアし、待っているスレッドを起こします:

- -
console.log(int32[0]); // 0;
-Atomics.store(int32, 0, 123);
-Atomics.wake(int32, 0, 1);
- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('Shared Memory', '#Atomics.wake', 'Atomics.wake')}}{{Spec2('Shared Memory')}}初期定義
- -

ブラウザ互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}} [2]{{CompatNo}}{{CompatGeckoDesktop("46")}} [1] [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("46")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

[1] 設定で無効になっています。about:config で javascript.options.shared_memorytrue に設定することで利用できます。

- -

[2] 現在実装中で、利用には次のオプションをつけて起動する必要があります:--js-flags=--harmony-sharedarraybuffer --enable-blink-feature=SharedArrayBuffer

- -

[3] バージョン 46 と 47 では Atomics.futexWake() という名前で利用できます。また引数 count の既定値は 0 となっています。列の代わりに Atomics.OK、Atomics.TIMEDOUT、Atomics.NOTEQUAL を返します

- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/global_objects/finalizationregistry/cleanupsome/index.html b/files/ja/web/javascript/reference/global_objects/finalizationregistry/cleanupsome/index.html deleted file mode 100644 index c25d3dd476..0000000000 --- a/files/ja/web/javascript/reference/global_objects/finalizationregistry/cleanupsome/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: FinalizationRegistry.prototype.cleanupSome() -slug: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry/cleanupSome -tags: - - FinalizationRegistry - - JavaScript - - Method - - Prototype - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry/cleanupSome ---- -
{{JSRef}}
- -

cleanupSome() メソッドは、 {{jsxref("FinalizationRegistry")}} 内のオブジェクトのうち、まだコールバックが呼ばれていないが回収されているオブジェクトの数が実装で選択された場合に、クリーンアップコールバックを起動します。このメソッドはオプションです。

- -

構文

- -
registry.cleanupSome([callback]);
-
- -

引数

- -
-
callback {{optional_inline}}
-
この cleanupSome への呼び出しによって起動されるコールバックだけに使用するコールバックを指定します。指定した場合、このコールバックは FinalizationRegistry で作成されたものの代わりに使用されます。
-
- -

返値

- -

undefined です。

- -

- -

通常、この関数を呼び出すことはありません。コールバックを適切に行うためには、 JavaScript エンジンのガベージコレクターに任せてください。この関数は主に、イベントループを発生させない、通常の JavaScript コードよりも WebAssembly で出てくる可能性の高い、長期に実行されるコードに対応するために存在します。また、コールバックが呼び出されない場合があることにも注意してください (例えば、ターゲットが回収されたレジストリ項目が存在しない場合)。

- -

レジストリからクリーンアップされる (クリーンアップコールバックを呼び出す) 回収オブジェクトの項目数は、実装で定義されています。実装によっては、対象となる項目を一つだけ削除したり、対象となるすべての項目を削除したり、あるいはその間のどこかで削除したりすることもあります。

- -

- -

cleanupSome の使用

- -
registry.cleanupSome?.(heldValue => {
-  // ...
-});
-
- -

このメソッドはオプションであり、実装によってはこのメソッドを持たない場合があります。詳細は HTML issue #5446 を参照してください。このメソッドはオプションなので、それを呼び出す前にそのメソッドが存在することを確認する必要があります。そのための一つの方法は、上の例のようにオプション連結 (?.) を使用することです。

- -

仕様書

- - - - - - - - - - - - -
仕様書
{{SpecName('WeakRefs', '#sec-finalization-registry.prototype.cleanupSome', 'FinalizationRegistry.prototype.cleanupSome')}}
- -

ブラウザーの互換性

- - - -

{{Compat("javascript.builtins.FinalizationRegistry.cleanupSome")}}

- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html b/files/ja/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html deleted file mode 100644 index 5705852c36..0000000000 --- a/files/ja/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Intl.DateTimeFormat.prototype -slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/prototype -tags: - - DateTimeFormat - - Internationalization - - JavaScript - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat -translation_of_original: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/prototype ---- -
{{JSRef}}
- -

Intl.DateTimeFormat.prototype プロパティは、 {{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}} コンストラクターに対するプロトタイプオブジェクトを表します。

- -
{{js_property_attributes(0, 0, 0)}}
- -

解説

- -

Intl.DateTimeFormat インスタンスの解説については {{jsxref("DateTimeFormat")}} を確認して下さい。

- -

{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} インスタンスは Intl.DateTimeFormat.prototype から継承します。プロトタイプオブジェクトへの変更はすべての {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} インスタンスによって継承されます。

- -

プロパティ

- -
-
Intl.DateTimeFormat.prototype.constructor
-
{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} への参照です。
-
- -

メソッド

- -
-
{{jsxref("DateTimeFormat.format", "Intl.DateTimeFormat.prototype.format()")}}
-
ロケールおよびこの {{jsxref("DateTimeFormat", "DateTimeFormat")}} オブジェクトの書式化オプションに則って日付を書式化するゲッター関数です。
-
{{jsxref("DateTimeFormat.formatToParts", "Intl.DateTimeFormat.prototype.formatToParts()")}}
-
Returns an {{jsxref("Array")}} of objects representing the date string in parts that can be used for custom locale-aware formatting.
-
{{jsxref("DateTimeFormat.resolvedOptions", "Intl.DateTimeFormat.prototype.resolvedOptions()")}}
-
ローケルを反映しているプロパティとオブジェクトの初期化中に計算されたオプションをもった新しいオブジェクトを返します。
-
{{jsxref("DateTimeFormat.formatRange", "Intl.DateTimeFormat.prototype.formatRange()")}}
-
This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating {{jsxref("DateTimeFormat", "DateTimeFormat")}}.
-
{{jsxref("DateTimeFormat.formatRangeToParts", "Intl.DateTimeFormat.prototype.formatRangeToParts()")}}
-
This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.
-
- -

仕様書

- - - - - - - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('ES Int Draft', '#sec-Intl.DateTimeFormat.prototype', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int Draft')}}
{{SpecName('ES Int 2.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int 2.0')}}
{{SpecName('ES Int 1.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int 1.0')}}初回定義
- -

ブラウザーの互換性

- -
- - -

{{Compat("javascript.builtins.Intl.DateTimeFormat.prototype")}}

-
- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/global_objects/webassembly/instance/prototype/index.html b/files/ja/web/javascript/reference/global_objects/webassembly/instance/prototype/index.html deleted file mode 100644 index fedccef945..0000000000 --- a/files/ja/web/javascript/reference/global_objects/webassembly/instance/prototype/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: WebAssembly.Instance.prototype -slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance -translation_of_original: Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/prototype ---- -
{{JSRef}} {{SeeCompatTable}}
- -

WebAssembly.Instance.prototype プロパティは {{jsxref("WebAssembly.Instance()")}} コンストラクタのプロトタイプを表します。

- -
{{js_property_attributes(0, 0, 0)}}
- -

説明

- -

全ての {{jsxref("WebAssembly.Instance")}} インスタンスは Instance.prototype を継承します。{{jsxref("WebAssembly.Instance()")}} コンストラクタのプロトタイプオブジェクトは全ての {{jsxref( "WebAssembly.Instance")}} インスタンスに影響するように変更可能です。 

- -

プロパティ

- -
-
Instance.prototype.constructor
-
このオブジェクトのインスタンスを生成した関数を返します。デフォルトでは  {{jsxref("WebAssembly.Instance()")}} コンストラクタです。
-
Instance.prototype.exports {{readonlyinline}}
-
WebAssembly モジュールインスタンスからエクスポートされた全ての関数をメンバとして持つオブジェクトを返します。これらは、JavaScriptからアクセスして使用することができます。
-
- -

メソッド

- -

なし。

- -

仕様

- - - - - - - - - - - - - - - - -
仕様策定状況コメント
{{SpecName('WebAssembly JS', '#webassemblymodule-objects', 'WebAssembly.Module()')}}{{Spec2('WebAssembly JS')}}初回ドラフト定義
- -

ブラウザ実装状況

- -
- - -

{{Compat("javascript.builtins.WebAssembly.Instance.prototype")}}

-
- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/global_objects/webassembly/memory/prototype/index.html b/files/ja/web/javascript/reference/global_objects/webassembly/memory/prototype/index.html deleted file mode 100644 index 6d837f2f73..0000000000 --- a/files/ja/web/javascript/reference/global_objects/webassembly/memory/prototype/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: WebAssembly.Memory.prototype -slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/prototype -tags: - - JavaScript - - Property - - Prototype - - WebAssembly - - memory -translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory -translation_of_original: Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/prototype ---- -
{{JSRef}} {{SeeCompatTable}}
- -

WebAssembly.Memory.prototype プロパティは {{jsxref("WebAssembly.Memory()")}} コンストラクタのプロトタイプを表します。

- -
{{js_property_attributes(0, 0, 0)}}
- -

説明

- -

全ての {{jsxref("WebAssembly.Memory")}} インスタンスは Memory.prototype を継承します。 {{jsxref("WebAssembly.Memory()")}} コンストラクタのプロトタイプオブジェクトは全ての {{jsxref( "WebAssembly.Memory")}} インスタンスに影響するように変更可能です。

- -

プロパティ

- -
-
Memory.prototype.constructor
-
このオブジェクトのインスタンスを生成した関数を返します。デフォルトでは {{jsxref("WebAssembly.Memory()")}} コンストラクタです。
-
{{jsxref("WebAssembly/Memory/buffer","Memory.prototype.buffer")}}
-
メモリーに格納されているバッファを返すアクセサプロパティ。
-
-

メソッド

-
-
{{jsxref("WebAssembly/Memory/grow","Memory.prototype.grow()")}}
-
指定した WebAssembly ページの数 (64KBを1単位とする) で Memory インスタンスのサイズを増やします。
-
- -

仕様

- - - - - - - - - - - - - - - - -
仕様策定状況コメント
{{SpecName('WebAssembly JS', '#webassemblymemory-objects', 'Memory')}}{{Spec2('WebAssembly JS')}}初回ドラフト定義
- -

ブラウザ実装状況

- -
- - -

{{Compat("javascript.builtins.WebAssembly.Memory.prototype")}}

-
- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/global_objects/webassembly/table/prototype/index.html b/files/ja/web/javascript/reference/global_objects/webassembly/table/prototype/index.html deleted file mode 100644 index 84709eb736..0000000000 --- a/files/ja/web/javascript/reference/global_objects/webassembly/table/prototype/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: WebAssembly.Table.prototype -slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/prototype -tags: - - JavaScript - - Property - - Prototype - - WebAssembly - - table -translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table -translation_of_original: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/prototype ---- -
{{JSRef}} {{SeeCompatTable}}
- -

WebAssembly.Table.prototype プロパティは {{jsxref("WebAssembly.Table()")}} コンストラクタのプロトタイプを表します。

- -
{{js_property_attributes(0, 0, 0)}}
- -

説明

- -

全ての {{jsxref("WebAssembly.Table")}} インスタンスは Table.prototype を継承します。{{jsxref("WebAssembly.Table()")}} コンストラクタのプロトタイプオブジェクトは全ての {{jsxref( "WebAssembly.Table")}} インスタンスに影響するように変更可能です。

- -

プロパティ

- -
-
Table.prototype.constructor
-
このオブジェクトのインスタンスを生成した関数を返します。デフォルトでは  {{jsxref("WebAssembly.Table()")}} コンストラクタです。
-
{{jsxref("WebAssembly/Table/length","Table.prototype.length")}}
-
テーブルの長さを返します。すなわち、要素数です。
-
-

メソッド

-
-
{{jsxref("WebAssembly/Table/get","Table.prototype.get()")}}
-
アクセサ関数。インデックスから格納された要素を取得します。
-
{{jsxref("WebAssembly/Table/grow","Table.prototype.grow()")}}
-
指定した要素数で Table インスタンスを拡張します。
-
{{jsxref("WebAssembly/Table/set","Table.prototype.set()")}}
-
指定したインデックスに要素を格納します。
-
- -

仕様

- - - - - - - - - - - - - - - - -
仕様策定状況コメント
{{SpecName('WebAssembly JS', '#webassemblytable-objects', 'Table')}}{{Spec2('WebAssembly JS')}}初回ドラフト定義
- -

ブラウザ実装状況

- -
- - -

{{Compat("javascript.builtins.WebAssembly.Table.prototype")}}

-
- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/operators/comparison_operators/index.html b/files/ja/web/javascript/reference/operators/comparison_operators/index.html deleted file mode 100644 index 5010c8eb89..0000000000 --- a/files/ja/web/javascript/reference/operators/comparison_operators/index.html +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: 比較演算子 -slug: Web/JavaScript/Reference/Operators/Comparison_Operators -tags: - - JavaScript - - Operator - - Reference - - 演算子 -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Comparison_Operators ---- -
{{jsSidebar("Operators")}}
- -

JavaScript には、厳密な比較と型変換の比較の両方があります。厳密な比較 (例: ===) は、オペランドが同じ型で、内容も一致している場合にのみ真になります。もっとよく使用される抽象的な比較 (例: ==) は、比較する前にオペランドを同じ型に変換します。抽象的な関係比較 (例: <=) では、比較前にまずオペランドがプリミティブ型に変換され、それから同じ型に変換されます。

- -

文字列は Unicode 値を使用した標準的な辞書順に基づいて比較されます。

- -
{{EmbedInteractiveExample("pages/js/expressions-equality.html")}}
- -
-
{{EmbedInteractiveExample("pages/js/expressions-strict-equality.html")}}
-
- -
- - - -

比較の機能は以下のとおりです。

- - - -

等価演算子

- -

等価 (==)

- -

等価演算子は、2 つのオペランドが同じ型でないならばオペランドを変換して、それから厳密な比較を行います。両方のオペランドがオブジェクトならば、 JavaScript は内部参照を比較するので、オペランドがメモリ内の同じオブジェクトを参照するときに等しくなります。

- -

構文

- -
x == y
-
- -

- -
1    ==  1         // true
-'1'  ==  1         // true
-1    == '1'        // true
-0    == false      // true
-0    == null       // false
-var object1 = {'key': 'value'}, object2 = {'key': 'value'};
-object1 == object2 // false
-0    == undefined  // false
-null == undefined  // true
-
- -

不等価 (!=)

- -

不等価演算子は、オペランド同士が等しくないならば真を返します。2 つのオペランドが同じ型でないならば、JavaScript は適切な型にオペランドを変換して比較しようとします。両方のオペランドがオブジェクトならば、JavaScript は内部参照を比較するので、オペランドがメモリ内の異なるオブジェクトを参照するときには等しくなりません。

- -

構文

- -
x != y
- -

- -
1 !=   2     // true
-1 !=  '1'    // false
-1 !=  "1"    // false
-1 !=  true   // false
-0 !=  false  // false
-
- -

一致 / 厳密等価 (===)

- -

厳密等価演算子は、型変換なしでオペランド同士が (上に示した通り) 厳密に等しければ真を返します。

- -

構文

- -
x === y
- -

- -
3 === 3   // true
-3 === '3' // false
-var object1 = {'key': 'value'}, object2 = {'key': 'value'};
-object1 === object2 //false
- -

不一致 / 厳密不等価 (!==)

- -

厳密不等価演算子は、オペランド同士が等しくないか、型が等しくない、あるいはその両方ならば真を返します。

- -

構文

- -
x !== y
- -

- -
3 !== '3' // true
-4 !== 3   // true
-
- -

関係演算子

- -

これらの演算子のそれぞれは、比較が行われる前に、そのオペランドをプリミティブに{{Glossary("Type_coercion", "型強制")}}します。両方とも文字列として終わる場合は、辞書順で比較され、そうでない場合は数値に変換されて比較されます。 NaN との比較は常に false を生み出します。

- -

大なり演算子 (>)

- -

大なり演算子は、左オペランドが右オペランドより大きければ、真を返します。

- -

構文

- -
x > y
- -

- -
4 > 3 // true
-
- -

大なりイコール演算子 (>=)

- -

大なりイコール演算子は、左オペランドが右オペランド以上ならば、真を返します。

- -

構文

- -
 x >= y
- -

- -
4 >= 3 // true
-3 >= 3 // true
-
- -

小なり演算子 (<)

- -

小なり演算子は、左オペランドが右オペランドより小さければ、真を返します。

- -

構文

- -
 x < y
- -

- -
3 < 4 // true
-
- -

小なりイコール演算子 (<=)

- -

小なりイコール演算子は、左オペランドが右オペランド以下ならば、真を返します。

- -

構文

- -
 x <= y
- -

- -
3 <= 4 // true
-3 <= 3 // true
-
- -

等価演算子の使用

- -

標準等価演算子 (==!=) は 2 つのオペランドの比較に抽象的等価比較アルゴリズムを使用します。オペランドの型が異なる場合は、比較を行う前にそれらを同じ型に変換しようとします。例えば 5 == '5' という式では、比較を行う前に右オペランドの文字列を数値に変換します。

- -

厳密等価演算子 (===!==) は厳密等価比較アルゴリズムを使用して、オペランドの型が同一かどうかに関する比較も行います。オペランドの型が異なれば、例えば 5'5' の比較では、同一性比較 5 !== '5'true と評価され、 5 === '5' のチェックは false 評価されます。

- -

厳密等価演算子を使うのは、オペランドが特定の型の特定の値でなければならない場合、言い換えればオペランドの正確な型が重要な場合です。それ以外では、2 つのオペランドが同じ型でなくても比較が可能になる、標準的な等価演算子を使えます。

- -

比較に型の変換が関わるとき (つまり厳密でない比較のとき)、 JavaScript は以下のように {{jsxref("String")}}, {{jsxref("Number")}}, {{jsxref("Boolean")}}, {{jsxref("Object")}} 型のオペランドを変換します。

- - - -
メモ: String オブジェクトはオブジェクト型であり、文字列型ではありません! String オブジェクトはほとんど使わないので、次の結果に驚くかもしれません。
- -
// 両方のオペランドが文字列型 (すなわちプリミティブな文字列) なので、true
-'foo' === 'foo'
-
-var a = new String('foo');
-var b = new String('foo');
-
-// a と b はオブジェクト型で、異なるオブジェクトを参照しているので、false
-a == b
-
-// a と b はオブジェクト型で、異なるオブジェクトを参照しているので、false
-a === b
-
-// a と 'foo' は異なる型で、比較前にオブジェクト (a) は
-// 文字列 'foo' に変換されるので、真
-a == 'foo'
- -

仕様書

- - - - - - - - - - - - - - - -
仕様書
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality Operators')}}
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}
- -

ブラウザーの互換性

- - - -

{{Compat("javascript.operators.comparison")}}

- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/operators/logical_operators/index.html b/files/ja/web/javascript/reference/operators/logical_operators/index.html deleted file mode 100644 index 8b43c3de26..0000000000 --- a/files/ja/web/javascript/reference/operators/logical_operators/index.html +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: 論理演算子 -slug: Web/JavaScript/Reference/Operators/Logical_Operators -tags: - - JavaScript - - Operator -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Logical_Operators ---- -
{{jsSidebar("Operators")}}
- -

概要

- -

{{ 原語併記("論理演算子", "Logical operators") }} は、基本的に真偽(論理)値とともに用いられ真偽値を返します。しかし、&& および || 演算子は真偽値ではない値も使うことができるため、その場合は、真偽値ではない値を返すことがあります。その場合の考え方は以下の「説明」の欄の記載の通りとなります。

- -

説明

- -

論理演算子を以下の表で説明します。:

- - - - - - - - - - - - - - - - - - - - - - - - -
演算子使用法説明
論理 AND(&&)expr1 && expr2expr1 を false と見ることができる場合は、expr1 を返します。そうでない場合は、expr2 を返します。したがって、真偽値と共に使われた場合、 演算対象の両方が true ならば、&& は、true を返し、そうでなければ、false を返します。
論理 OR (||)expr1 || expr2expr1 を true と見ることができる場合は、expr1 を返します。そうでない場合は、expr2 を返します。したがって、真偽値と共に使われた場合、 演算対象のどちらかが true ならば、|| は、true を返し、両方とも false の場合は、false を返します。
論理 NOT (!)!expr単一の演算対象が true と見ることができる場合は、false を返します。そうでない場合は、true を返します。
- -

true に変換できる値は、いわゆる {{Glossary("truthy")}} です。false に変換できる値は、いわゆる {{Glossary("falsy")}} です。

- -

false と見ることができる式の例は、null、0、空文字列 ("")、あるいは、undefined と評価されるものです。

- -

&&|| 演算子が真偽値ではない値である演算対象とともに用いることができても、それらは、真偽演算子と考えることができます。なぜなら、それらの戻り値は、常に、真偽値と見ることができるからです。

- -

ショートサーキット評価

- -

論理演算子は左から右へ評価されるため、論理演算子で左辺を評価した時点で論理式の結果が確定した場合には右辺の評価を行わないことを、ショートサーキット評価といいます。例えば、A && Bという論理式があった場合、Aがfalseなら、その時点で式全体の結果はfalseで確定するため、Bがどうであるかについてはチェックしません。:

- - - -

 上記の式の anything の部分は評価されません。また、上記の式の anything の部分は (括弧で示しているとおり) ひとつの論理式ですので注意してください。

- -

例えば、以下の 2 つの関数は等価です。

- -
function shortCircuitEvaluation() {
-  doSomething() || doSomethingElse()
-}
-
-function equivalentEvaluation() {
-  var flag = doSomething();
-  if (!flag) {
-    doSomethingElse();
-  }
-}
-
- -

しかし、以下の式は等価ではありません。これは演算子の優先順位のためであり、右側の演算子をひとつの式にする (必要に応じて括弧でグループ化する) 必要性の重要度を高めています。

- -
false && true  || true      // true を返す
-false && (true || true)     // false を返す
- -

論理 AND (&&)

- -

以下のコードは、&& (論理 AND) 演算子の例を示しています。

- -
a1 = true  && true      // t && t true を返します。
-a2 = true  && false     // t && f false を返します。
-a3 = false && true      // f && t false を返します。
-a4 = false && (3 == 4)  // f && f false を返します。
-a5 = "Cat" && "Dog"     // t && t "Dog" を返します。
-a6 = false && "Cat"     // f && t false を返します。
-a7 = "Cat" && false     // t && f false を返します。
-
- -

論理 OR (||)

- -

以下のコードは、|| (論理 OR) 演算子の例を示しています。

- -
o1 = true  || true       // t || t true を返します。
-o2 = false || true       // f || t true を返します。
-o3 = true  || false      // t || f true を返します。
-o4 = false || (3 == 4)   // f || f false を返します。
-o5 = "Cat" || "Dog"      // t || t "Cat" を返します。
-o6 = false || "Cat"      // f || t "Cat" を返します。
-o7 = "Cat" || false      // t || f "Cat" を返します。
-
- -

論理 NOT (!)

- -

以下のコードは、! (論理 NOT) 演算子の例を示しています。

- -
n1 = !true              // !t false を返します。
-n2 = !false             // !f true を返します。
-n3 = !"Cat"             // !t false を返します。
-
- -

変換規則

- -

AND から OR への変換

- -

Boolean について以下の演算を行います:

- -
bCondition1 && bCondition2
- -

これは以下の演算と等価です:

- -
!(!bCondition1 || !bCondition2)
- -

OR から AND への変換

- -

Boolean について以下の演算を行います:

- -
bCondition1 || bCondition2
- -

これは以下の演算と等価です:

- -
!(!bCondition1 && !bCondition2)
- -

NOT 間の変換

- -

Boolean について以下の演算を行います:

- -
!!bCondition
- -

これは以下の演算と等価です:

- -
bCondition
- -

入れ子の括弧を削除する

- -

論理演算子は左から右へ評価されるため、複雑な式の中にある括弧をいくつかの規則に従って削除することができます。

- -

入れ子の AND を削除する

- -

Boolean について以下の複雑な演算を行います:

- -
bCondition1 || (bCondition2 && bCondition3)
- -

これは以下の演算と等価です:

- -
bCondition1 || bCondition2 && bCondition3
- -

入れ子の OR を削除する

- -

Boolean について以下の複雑な演算を行います:

- -
bCondition1 && (bCondition2 || bCondition3)
- -

これは以下の演算と等価です:

- -
!(!bCondition1 || !bCondition2 && !bCondition3)
- -

仕様

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
仕様書策定状況コメント
{{SpecName('ES1')}}{{Spec2('ES1')}}最初期の定義
{{SpecName('ES5.1', '#sec-11.11')}}{{Spec2('ES5.1')}}仕様書内のいくつかのセクションで定義: Logical NOT Operator, Binary Logical Operators
{{SpecName('ES6', '#sec-binary-logical-operators')}}{{Spec2('ES6')}}仕様書内のいくつかのセクションで定義: Logical NOT Operator, Binary Logical Operators
{{SpecName('ESDraft', '#sec-binary-logical-operators')}}{{Spec2('ESDraft')}}仕様書内のいくつかのセクションで定義: Logical NOT Operator, Binary Logical Operators
- -

ブラウザ実装状況

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
機能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
論理 AND (&&){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
論理 OR (||){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
論理 NOT (!){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
機能AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
論理 AND (&&){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
論理 OR (||){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
論理 NOT (!){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

関連情報

- - diff --git a/files/ja/web/javascript/reference/operators/special/index.html b/files/ja/web/javascript/reference/operators/special/index.html deleted file mode 100644 index cb220a008d..0000000000 --- a/files/ja/web/javascript/reference/operators/special/index.html +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Special -slug: Web/JavaScript/Reference/Operators/Special ---- -This page was auto-generated because a user created a sub-page to this page. diff --git a/files/ja/web/javascript/reference/operators/special_operators/index.html b/files/ja/web/javascript/reference/operators/special_operators/index.html deleted file mode 100644 index febf3ac3d6..0000000000 --- a/files/ja/web/javascript/reference/operators/special_operators/index.html +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Special Operators -slug: Web/JavaScript/Reference/Operators/Special_Operators ---- -This page was auto-generated because a user created a sub-page to this page. diff --git a/files/ja/web/javascript/reference/reserved_words/index.html b/files/ja/web/javascript/reference/reserved_words/index.html deleted file mode 100644 index fabc275890..0000000000 --- a/files/ja/web/javascript/reference/reserved_words/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: 予約語 -slug: Web/JavaScript/Reference/Reserved_Words -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/Lexical_grammar#Keywords -translation_of_original: Web/JavaScript/Reference/Reserved_Words ---- -

以下は予約語であり、変数、関数、メソッド、あるいはオブジェクトの識別子として用いることはできません。以下は ECMAScript の仕様で既存のキーワードとして予約されているものです。

- -
- -
- -

将来の使用を見越した予約語

- -

以下は ECMAScript の仕様で将来のキーワードとして予約されているものです。現在は特別な機能を持っていませんが、将来機能を持つときのために、識別子として使用できません。このキーワードは、厳格モード、非厳格モードの両方で使用できません。

- -
注記: Firefox 5 (JavaScript 1.8.6) より以前では、これらのキーワードは厳格モードでないときには使用できました。この ECMAScript 違反は Firefox 5 で修正されました。
- -
- -
- -

以下は 厳格モードのコード として実行されたときに 、ECMAScript の仕様で将来のキーワードとして 予約されているものです。ただし、JavaScript 1.7 以上では letyield は伝統的な Mozilla 特有の機能を持っています。

- -
- -
- -

const は ECMAScript の仕様によって将来のキーワードとして予約されていますが、Mozilla やほとんどの他のブラウザが非標準の拡張として実装していることに注意してください。さらに、 exportimport はかつて Mozilla で実装されていましたが、現在では予約語となっています。

- -

加えて、 nulltruefalse リテラルは ECMAScript の仕様で予約されています。

- -

予約語の利用

- -

実際に、予約語は識別子のみに適用されます。es5.github.com/#A.1 の記述にあるように、これらは全て予約語を排除しない識別名です。

- -

a.import
- a["import"]
- a = { import: "test" }.

- -

反対に、以下は識別子であるので違反です。識別子は関数宣言や関数式に使用されます。

- -

function import() {}

diff --git a/files/ja/web/javascript/reference/statements/yield/index.html b/files/ja/web/javascript/reference/statements/yield/index.html deleted file mode 100644 index 69be44e8d9..0000000000 --- a/files/ja/web/javascript/reference/statements/yield/index.html +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: yield -slug: Web/JavaScript/Reference/Statements/yield -translation_of: Web/JavaScript/Reference/Operators/yield -translation_of_original: Web/JavaScript/Reference/Statements/yield ---- -

JavaScript 1.7 の新機能』、『イテレータとジェネレータ』 を参照して下さい。

-- cgit v1.2.3-54-g00ecf