From a065e04d529da1d847b5062a12c46d916408bf32 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 21:46:22 -0500 Subject: update based on https://github.com/mdn/yari/issues/2028 --- .../ru/web/accessibility/at-apis/gecko/index.html | 9 - .../accessibility/at-apis/gecko/roles/index.html | 498 ------------- .../at-apis/gecko/roles/role_document/index.html | 31 - .../gecko/roles/role_password_text/index.html | 27 - files/ru/web/accessibility/at-apis/index.html | 176 ----- files/ru/web/api/devicestorage/index.html | 87 --- files/ru/web/api/fmradio/index.html | 94 --- files/ru/web/api/identitymanager/index.html | 47 -- .../ru/web/api/identitymanager/request/index.html | 88 --- .../ru/web/api/navigator/getdatastores/index.html | 58 -- files/ru/web/api/navigator/id/index.html | 20 - .../navigator/mozaudiochannelmanager/index.html | 32 - files/ru/web/api/navigator/mozcamera/index.html | 43 -- files/ru/web/api/navigator/mozl10n/index.html | 38 - files/ru/web/api/navigator/moznfc/index.html | 43 -- files/ru/web/api/webfm_api/index.html | 156 ---- files/ru/web/css/-moz-binding/index.html | 115 --- .../ru/web/events/dommodaldialogclosed/index.html | 63 -- files/ru/web/events/domsubtreemodified/index.html | 21 - .../guide/liveconnect_overview/index.html | 795 --------------------- .../javascript/new_in_javascript/1.5/index.html | 37 - .../javascript/new_in_javascript/1.6/index.html | 32 - .../javascript/new_in_javascript/1.8.1/index.html | 31 - .../javascript/new_in_javascript/1.8.5/index.html | 122 ---- .../javascript/new_in_javascript/1.8/index.html | 38 - .../ecmascript_5_support_in_mozilla/index.html | 46 -- .../ecmascript_6_support_in_mozilla/index.html | 222 ------ .../ru/web/javascript/new_in_javascript/index.html | 80 --- .../functions/arguments/caller/index.html | 100 --- .../global_objects/array/observe/index.html | 138 ---- .../global_objects/date/tolocaleformat/index.html | 73 -- .../global_objects/function/arity/index.html | 30 - .../global_objects/function/isgenerator/index.html | 83 --- .../reference/global_objects/iterator/index.html | 138 ---- .../global_objects/number/tointeger/index.html | 94 --- .../global_objects/object/count/index.html | 83 --- .../global_objects/object/eval/index.html | 81 --- .../global_objects/object/getnotifier/index.html | 47 -- .../global_objects/object/nosuchmethod/index.html | 195 ----- .../global_objects/object/observe/index.html | 142 ---- .../global_objects/object/parent/index.html | 75 -- .../global_objects/object/unobserve/index.html | 97 --- .../global_objects/object/unwatch/index.html | 93 --- .../global_objects/object/watch/index.html | 168 ----- .../global_objects/parallelarray/index.html | 52 -- .../global_objects/string/quote/index.html | 124 ---- .../operators/array_comprehensions/index.html | 241 ------- .../operators/expression_closures/index.html | 118 --- .../operators/generator_comprehensions/index.html | 229 ------ .../reference/statements/for_each...in/index.html | 126 ---- 50 files changed, 5576 deletions(-) delete mode 100644 files/ru/web/accessibility/at-apis/gecko/index.html delete mode 100644 files/ru/web/accessibility/at-apis/gecko/roles/index.html delete mode 100644 files/ru/web/accessibility/at-apis/gecko/roles/role_document/index.html delete mode 100644 files/ru/web/accessibility/at-apis/gecko/roles/role_password_text/index.html delete mode 100644 files/ru/web/accessibility/at-apis/index.html delete mode 100644 files/ru/web/api/devicestorage/index.html delete mode 100644 files/ru/web/api/fmradio/index.html delete mode 100644 files/ru/web/api/identitymanager/index.html delete mode 100644 files/ru/web/api/identitymanager/request/index.html delete mode 100644 files/ru/web/api/navigator/getdatastores/index.html delete mode 100644 files/ru/web/api/navigator/id/index.html delete mode 100644 files/ru/web/api/navigator/mozaudiochannelmanager/index.html delete mode 100644 files/ru/web/api/navigator/mozcamera/index.html delete mode 100644 files/ru/web/api/navigator/mozl10n/index.html delete mode 100644 files/ru/web/api/navigator/moznfc/index.html delete mode 100644 files/ru/web/api/webfm_api/index.html delete mode 100644 files/ru/web/css/-moz-binding/index.html delete mode 100644 files/ru/web/events/dommodaldialogclosed/index.html delete mode 100644 files/ru/web/events/domsubtreemodified/index.html delete mode 100644 files/ru/web/javascript/guide/liveconnect_overview/index.html delete mode 100644 files/ru/web/javascript/new_in_javascript/1.5/index.html delete mode 100644 files/ru/web/javascript/new_in_javascript/1.6/index.html delete mode 100644 files/ru/web/javascript/new_in_javascript/1.8.1/index.html delete mode 100644 files/ru/web/javascript/new_in_javascript/1.8.5/index.html delete mode 100644 files/ru/web/javascript/new_in_javascript/1.8/index.html delete mode 100644 files/ru/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html delete mode 100644 files/ru/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html delete mode 100644 files/ru/web/javascript/new_in_javascript/index.html delete mode 100644 files/ru/web/javascript/reference/functions/arguments/caller/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/array/observe/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/date/tolocaleformat/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/function/arity/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/function/isgenerator/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/iterator/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/number/tointeger/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/count/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/eval/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/getnotifier/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/nosuchmethod/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/observe/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/parent/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/unobserve/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/unwatch/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/object/watch/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/parallelarray/index.html delete mode 100644 files/ru/web/javascript/reference/global_objects/string/quote/index.html delete mode 100644 files/ru/web/javascript/reference/operators/array_comprehensions/index.html delete mode 100644 files/ru/web/javascript/reference/operators/expression_closures/index.html delete mode 100644 files/ru/web/javascript/reference/operators/generator_comprehensions/index.html delete mode 100644 files/ru/web/javascript/reference/statements/for_each...in/index.html (limited to 'files/ru/web') diff --git a/files/ru/web/accessibility/at-apis/gecko/index.html b/files/ru/web/accessibility/at-apis/gecko/index.html deleted file mode 100644 index 9cd605e79d..0000000000 --- a/files/ru/web/accessibility/at-apis/gecko/index.html +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Gecko -slug: Web/Accessibility/AT-APIs/Gecko -tags: - - NeedsTranslation - - TopicStub -translation_of: Mozilla/Tech/Accessibility/AT-APIs/Gecko ---- -{{wiki.localize('System.API.page-generated-for-subpage')}} diff --git a/files/ru/web/accessibility/at-apis/gecko/roles/index.html b/files/ru/web/accessibility/at-apis/gecko/roles/index.html deleted file mode 100644 index 3279dc94f1..0000000000 --- a/files/ru/web/accessibility/at-apis/gecko/roles/index.html +++ /dev/null @@ -1,498 +0,0 @@ ---- -title: Gecko Roles -slug: Web/Accessibility/AT-APIs/Gecko/Roles -tags: - - AT_APIs - - Accessibility - - NeedsTranslation - - Reference - - TopicStub -translation_of: Mozilla/Tech/Accessibility/AT-APIs/Gecko/Roles ---- -

« AT APIs Support Page

-

This page offers a list of accessible roles used in Gecko. Role constants are defined in the nsIAccessibleRole interface.

-
-
- ROLE_NOTHING
-
- Used when the accessible item doesn't have a strongly defined role.
-
- ROLE_TITLEBAR
-
- Represents a title or caption bar for a window. Used by MSAA only, this is supported automatically by Microsoft Windows.
-
- ROLE_MENUBAR
-
- Represents the menu bar (positioned beneath the title bar of a window on most platforms or at the top of the screen on Mac OS X) from which menus are selected by the user.
-
- ROLE_SCROLLBAR
-
- Represents a vertical or horizontal scroll bar, which is part of the client area or used in a control.
-
- ROLE_GRIP
-
- Represents a special mouse pointer, which allows a user to manipulate user interface elements such as windows. For example, a user clicks and drags a sizing grip in the lower-right corner of a window to resize it
-
- ROLE_SOUND
-
- Represents a system sound, which is associated with various system events.
-
- ROLE_CURSOR
-
- Represents the system mouse pointer.
-
- ROLE_CARET
-
- Represents the system caret.
-
- ROLE_ALERT
-
- Represents an alert or a condition that a user should be notified about. Assistive Technologies typically respond to the role by reading the entire onscreen contents of containers advertising this role. Should be used for warning dialogs, etc.
-
- ROLE_WINDOW
-
- Represents the window frame, which contains child objects such as a title bar, client, and other objects contained in a window. The role is supported automatically by Microsoft Windows.
-
- ROLE_INTERNAL_FRAME
-
- A sub-document.
-
- ROLE_MENUPOPUP
-
- Represents a menu, which presents a list of options from which the user can make a selection to perform an action.
-
- ROLE_MENUITEM
-
- Represents a menu item, which is an entry in a menu that a user can choose to carry out a command, select an option.
-
- ROLE_TOOLTIP
-
- Represents a tooltip that provides helpful hints; this is generally displayed at the mouse cursor position.
-
- ROLE_APPLICATION
-
- Represents a main window for an application.
-
- ROLE_DOCUMENT
-
- Represents a document window. A document window is always contained within an application window.
-
- ROLE_PANE
-
- Represents a pane within a frame or document window. Users can navigate between panes and within the contents of the current pane, but cannot navigate between items in different panes. Thus, panes represent a level of grouping lower than frame windows or documents, but above individual controls.
-
- ROLE_CHART
-
- Represents a graphical image used to represent data.
-
- ROLE_DIALOG
-
- Represents a dialog box or message box.
-
- ROLE_BORDER
-
- Represents a window border.
-
- ROLE_GROUPING
-
- Logically groups other objects.
-
- ROLE_SEPARATOR
-
- Used to visually divide a space into two regions, such as a separator menu item or a bar that divides split panes within a window.
-
- ROLE_TOOLBAR
-
- Represents a toolbar, which is a grouping of controls (push buttons or toggle buttons) that provides easy access to frequently used features.
-
- ROLE_STATUSBAR
-
- Represents a status bar, which is an area at the bottom of a window that displays information about the current operation, state of the application, or selected object. The status bar has multiple fields, which display different kinds of information.
-
- ROLE_TABLE
-
- Represents a table that contains rows and columns of cells, and optionally, row headers and column headers.
-
- ROLE_COLUMNHEADER
-
- Represents a column header, providing a visual label for a column in a table.
-
- ROLE_ROWHEADER
-
- Represents a row header, which provides a visual label for a table row.
-
- ROLE_COLUMN
-
- Represents a column of cells within a table.
-
- ROLE_ROW
-
- Represents a row of cells within a table.
-
- ROLE_CELL
-
- Represents a cell within a table.
-
- ROLE_LINK
-
- Represents a link to something else. This object might look like text or a graphic, but it acts like a button.
-
- ROLE_HELPBALLOON
-
- Displays a Help topic in the form of a ToolTip or Help balloon.
-
- ROLE_CHARACTER
-
- Represents a cartoon-like graphic object, such as Microsoft Office Assistant, which is displayed to provide help to users of an application.
-
- ROLE_LIST
-
- Represents a list box, allowing the user to select one or more items.
-
- ROLE_LISTITEM
-
- Represents an item in a list.
-
- ROLE_OUTLINE
-
- Represents an outline or tree structure, such as a tree view control, that displays a hierarchical list and allows the user to expand and collapse branches.
-
- ROLE_OUTLINEITEM
-
- Represents an item in an outline or tree structure.
-
- ROLE_PAGETAB
-
- Represents a page tab, it is a child of a page tab list.
-
- ROLE_PROPERTYPAGE
-
- Represents a property sheet.
-
- ROLE_INDICATOR
-
- Represents an indicator, such as a pointer graphic, that points to the current item.
-
- ROLE_GRAPHIC
-
- Represents a picture.
-
- ROLE_STATICTEXT
-
- Represents read-only text, such as labels for other controls or instructions in a dialog box. Static text cannot be modified or selected.
-
- ROLE_TEXT_LEAF
-
- Represents selectable text that allows edits or is designated read-only.
-
- ROLE_PUSHBUTTON
-
- Represents a push button control.
-
- ROLE_CHECKBUTTON
-
- Represents a check box control.
-
- ROLE_RADIOBUTTON
-
- Represents an option button, also called a radio button. It is one of a group of mutually exclusive options. All objects sharing a single parent that have this attribute are assumed to be part of single mutually exclusive group.
-
- ROLE_COMBOBOX
-
- Represents a combo box; an edit control with an associated list box that provides a set of predefined choices.
-
- ROLE_DROPLIST
-
- Represents the calendar control.
-
- ROLE_PROGRESSBAR
-
- Represents a progress bar, dynamically showing the user the percent complete of an operation in progress.
-
- ROLE_DIAL
-
- Represents a dial or knob whose purpose is to allow a user to set a value.
-
- ROLE_HOTKEYFIELD
-
- Represents a hot-key field that allows the user to enter a combination or sequence of keystrokes.
-
- ROLE_SLIDER
-
- Represents a slider, which allows the user to adjust a setting in given increments between minimum and maximum values.
-
- ROLE_SPINBUTTON
-
- Represents a spin box, which is a control that allows the user to increment or decrement the value displayed in a separate "buddy" control associated with the spin box.
-
- ROLE_DIAGRAM
-
- Represents a graphical image used to diagram data.
-
- ROLE_ANIMATION
-
- Represents an animation control, which contains content that changes over time, such as a control that displays a series of bitmap frames.
-
- ROLE_EQUATION
-
- Represents a mathematical equation. It is used by MATHML.
-
- ROLE_BUTTONDROPDOWN
-
- Represents a button that drops down a list of items.
-
- ROLE_BUTTONMENU
-
- Represents a button that drops down a menu.
-
- ROLE_BUTTONDROPDOWNGRID
-
- Represents a button that drops down a grid.
-
- ROLE_WHITESPACE
-
- Represents blank space between other objects.
-
- ROLE_PAGETABLIST
-
- Represents a container of page tab controls.
-
- ROLE_CLOCK
-
- Represents a control that displays time.
-
- ROLE_SPLITBUTTON
-
- Represents a button on a toolbar that has a drop-down list icon directly adjacent to the button.
-
- ROLE_IPADDRESS
-
- Represents an edit control designed for an Internet Protocol (IP) address. The edit control is divided into sections for the different parts of the IP address.
-
- ROLE_ACCEL_LABEL
-
- Represents a label control that has an accelerator.
-
- ROLE_ARROW
-
- Represents an arrow in one of the four cardinal directions.
-
- ROLE_CANVAS
-
- Represents a control that can be drawn into and is used to trap events.
-
- ROLE_CHECK_MENU_ITEM
-
- Represents a menu item with a check box.
-
- ROLE_COLOR_CHOOSER
-
- Represents a specialized dialog that lets the user choose a color.
-
- ROLE_DATE_EDITOR
-
- Represents control whose purpose is to allow a user to edit a date.
-
- ROLE_DESKTOP_ICON
-
- An iconified internal frame in an ROLE_DESKTOP_PANE.
-
- ROLE_DESKTOP_FRAME
-
- A desktop pane. A pane that supports internal frames and iconified versions of those internal frames.
-
- ROLE_DIRECTORY_PANE
-
- A directory pane. A pane that allows the user to navigate through and select the contents of a directory. May be used by a file chooser.
-
- ROLE_FILE_CHOOSER
-
- A file chooser. A specialized dialog that displays the files in the directory and lets the user select a file, browse a different directory, or specify a filename. May use the directory pane to show the contents of a directory.
-
- ROLE_FONT_CHOOSER
-
- A font chooser. A font chooser is a component that lets the user pick various attributes for fonts.
-
- ROLE_CHROME_WINDOW
-
- Frame role. A top level window with a title bar, border, menu bar, etc. It is often used as the primary window for an application.
-
- ROLE_GLASS_PANE
-
- A glass pane. A pane that is guaranteed to be painted on top of all panes beneath it.
-
- ROLE_HTML_CONTAINER
-
- A document container for HTML, whose children represent the document content.
-
- ROLE_ICON
-
- A small fixed size picture, typically used to decorate components.
-
- ROLE_LABEL
-
- Presents an icon or short string in an interface.
-
- ROLE_LAYERED_PANE
-
- A layered pane. A specialized pane that allows its children to be drawn in layers, providing a form of stacking order. This is usually the pane that holds the menu bar as well as the pane that contains most of the visual components in a window.
-
- ROLE_OPTION_PANE
-
- A specialized pane whose primary use is inside a dialog.
-
- ROLE_PASSWORD_TEXT
-
- A text object uses for passwords, or other places where the text content is not shown visibly to the user.
-
- ROLE_POPUP_MENU
-
- A temporary window that is usually used to offer the user a list of choices, and then hides when the user selects one of those choices.
-
- ROLE_RADIO_MENU_ITEM
-
- A radio button that is a menu item.
-
- ROLE_ROOT_PANE
-
- A root pane. A specialized pane that has a glass pane and a layered pane as its children. Its children can include scroll bars and a viewport.
-
- ROLE_SCROLL_PANE
-
- A scroll pane. An object that allows a user to incrementally view a large amount of information.
-
- ROLE_SPLIT_PANE
-
- A split pane. A specialized panel that presents two other panels at the same time. Between the two panels is a divider the user can manipulate to make one panel larger and the other panel smaller.
-
- ROLE_TABLE_COLUMN_HEADER
-
- The header for a column of a table.
-
- ROLE_TABLE_ROW_HEADER
-
- The header for a row of a table.
-
- ROLE_TEAR_OFF_MENU_ITEM
-
- A menu item used to tear off and reattach its menu.
-
- ROLE_TERMINAL
-
- Represents an accessible terminal.
-
- ROLE_TEXT_CONTAINER
-
- Collection of objects that constitute a logical text entity.
-
- ROLE_TOGGLE_BUTTON
-
- A toggle button. A specialized push button that can be checked or unchecked, but does not provide a separate indicator for the current state.
-
- ROLE_TREE_TABLE
-
- Representas a control that is capable of expanding and collapsing rows as well as showing multiple columns of data.
-
- ROLE_VIEWPORT
-
- A viewport. An object usually used in a scroll pane. It represents the portion of the entire data that the user can see. As the user manipulates the scroll bars, the contents of the viewport can change.
-
- ROLE_HEADER
-
- Header of a document page.
-
- ROLE_FOOTER
-
- Footer of a document page.
-
- ROLE_PARAGRAPH
-
- A paragraph of text.
-
- ROLE_RULER
-
- A ruler such as those used in word processors.
-
- ROLE_AUTOCOMPLETE
-
- A text entry having dialog or list containing items for insertion into an entry widget, for instance a list of words for completion of a text entry.
-
- ROLE_EDITBAR
-
- An editable text object in a toolbar.
-
- ROLE_ENTRY
-
- An control whose textual content may be entered or modified by the user.
-
- ROLE_CAPTION
-
- A caption describing another object.
-
- ROLE_DOCUMENT_FRAME
-
- A visual frame or container which contains a view of document content. Document frames may occur within another Document instance, in which case the second document may be said to be embedded in the containing instance. HTML frames are often ROLE_DOCUMENT_FRAME. Either this object, or a singleton descendant, should implement the Document interface.
-
- ROLE_HEADING
-
- Heading.
-
- ROLE_PAGE
-
- An object representing a page of document content. It is used in documents which are accessed by the user on a page by page basis.
-
- ROLE_SECTION
-
- A container of document content.
-
- ROLE_REDUNDANT_OBJECT
-
- An object which is redundant with another object in the accessible hierarchy. ATs typically ignore objects with this role.
-
- ROLE_FORM
-
- A container of form controls.
-
- ROLE_IME
-
- An object which is used to allow input of characters not found on a keyboard, such as the input of Chinese characters on a Western keyboard.
-
- ROLE_APP_ROOT
-
-  ???
-
- ROLE_PARENT_MENUITEM
-
- Represents a menu item, which is an entry in a menu that a user can choose to display another menu.
-
- ROLE_CALENDAR
-
- A calendar that allows the user to select a date.
-
- ROLE_COMBOBOX_LIST
-
- A list of items that is shown by combobox.
-
- ROLE_COMBOBOX_OPTION
-
- A item of list that is shown by combobox
-
- ROLE_IMAGE_MAP
-
- An image map -- has child links representing the areas
-
- ROLE_OPTION
-
- An option in a listbox
-
- ROLE_RICH_OPTION
-
- A rich option in a listbox, it can have other widgets as children
-
- ROLE_LISTBOX
-
- A list of options
-
-
-

Editor's note: Use template ROLE_ to get reference on accessible role. It looks like ROLE_MENUITEM.

-
diff --git a/files/ru/web/accessibility/at-apis/gecko/roles/role_document/index.html b/files/ru/web/accessibility/at-apis/gecko/roles/role_document/index.html deleted file mode 100644 index 0116e62762..0000000000 --- a/files/ru/web/accessibility/at-apis/gecko/roles/role_document/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: ROLE_DOCUMENT -slug: Web/Accessibility/AT-APIs/Gecko/Roles/ROLE_DOCUMENT -translation_of: Mozilla/Tech/Accessibility/AT-APIs/Gecko/Roles/ROLE_DOCUMENT ---- -

« Gecko Roles Page

-

Represents a document window. A document window is always contained within an application window.

-

Interfaces

- -

Mapped to

- -

Used by

- -

diff --git a/files/ru/web/accessibility/at-apis/gecko/roles/role_password_text/index.html b/files/ru/web/accessibility/at-apis/gecko/roles/role_password_text/index.html deleted file mode 100644 index 3157da6c12..0000000000 --- a/files/ru/web/accessibility/at-apis/gecko/roles/role_password_text/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: ROLE PASSWORD TEXT -slug: Web/Accessibility/AT-APIs/Gecko/Roles/ROLE_PASSWORD_TEXT -translation_of: Mozilla/Tech/Accessibility/AT-APIs/Gecko/Roles/ROLE_PASSWORD_TEXT ---- -

 

- -

« Gecko Roles Page

- -

Description

- -

A text object uses for passwords, or other places where the text content is not shown visibly to the user.

- -

Mapped to

- - - -

Used by

- - diff --git a/files/ru/web/accessibility/at-apis/index.html b/files/ru/web/accessibility/at-apis/index.html deleted file mode 100644 index 43b7f1d8b6..0000000000 --- a/files/ru/web/accessibility/at-apis/index.html +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: AT APIs Support -slug: Web/Accessibility/AT-APIs -tags: - - AT_APIs - - Accessibility - - NeedsTranslation - - TopicStub -translation_of: Mozilla/Tech/Accessibility/AT-APIs ---- -

Introduction

- -
Documentation is in progress still. But in the meantime it more up-to-date and contains more details than existed analogues for AT-SPI and MSAA
- -

This documentation explains how makers of screen readers, voice dictation packages, onscreen keyboards, magnification software and other assitive technologies can support Gecko-based software. We provide for them the support of these products on Windows, Linux/Unix and OS X platforms.

- -

Accessible Gecko

- -

Gecko is a rendering engine that Firefox, SeaMonkey, Netscape and yelp use. Gecko can render a variety of content, not just HTML and supports key web standards such as Cascading Style Sheets, Javascript and the W3C DOM. Gecko also handles the users keystrokes and mouse clicks. Gecko is the core architecture that we are adding accessibility to, in order to support basic accessibility in all applications that are based on it.

- -

Gecko Based Applications

- -

Gecko can be used in two ways to create application:

- -

Embedded Clients

- -

Embedded clients use Gecko only in the content window, at the moment for HTML and generic XML only. They typically use standard Windows controls for their user interface -- the area outside of the client content window, plus the context menu.

- - - -

XUL Applications

- -

XUL applications make full use of the Gecko architecture, not only for HTML content, but also for the entire user interface. Widgets such as menus, tab panels, tree views and dialogs are provided via an XML language called XUL (eXtensible User-interface Language). None of the user interface contains standard OS controls. This is done to ensure a common look and feel across all supported platforms, and to allow for different skins (appearances). Developing a XUL window is not that different from developing a web page, but the elements available to add widgets are more powerful and designed to be similar to desktop widgets.

- -

Examples of XUL applications:

- - - -

Gecko Version

- -

For Firefox and all other Gecko-based products: this documentation applies to up-to-date product builds based on Gecko 1.9.2 -- currently not available on official releases. However most of described features are supported starting from Gecko 1.9.0 (Firefox 3.0). However it's preferable to grab the current build of Firefox or any other Gecko-based product to be up to dated:

- - - -

Determining if Accessibility is Enabled in a Firefox

- -

Accessibility is enabled on Windows and Linux platforms by default. As well you might find helpful the about:accessibilityenabled Firefox extension.

- -

Supported AT APIs

- -

AT APIs terms

- -
-
Microsoft Active Accessibility (MSAA)
-
an API devised by Microsoft so that accessibility aids can track what's going on inside the user interface of any software package that supports it. If you seriously need to understand MSAA, you'll need to read the docs on MSDN and play with the sample apps and code that come with MSAA SDK 1.3. (I recommend SDK 1.3 because the MSAA SDK 2.0 doesn't come with the source code to the testing tools. The other differences are not important).
-
IAccessible2 (IA2)
-
IAccessible2 is a new accessibility API which complements Microsoft's earlier work on MSAA. This API fills critical accessibility API gaps in the MSAA offering.
-
Assistive Technology Service Provider Interface (AT-SPI)
-
an API devised by Sun Microsystems so that accessibility aids can track what's going on inside the user interface of any software package that supports it. If you seriously need to understand AT-SPI, you'll need to read the docs on gnome.org and play with the available sample apps and code, such as at-poke. Please note that the web docs are sometimes out of date, and the latest AT-SPI is available on CVS.
-
Universal Access (UA)
-
Universal Access (UA) is the Apple's accessibility framework.
-
- -

Windows platform

- -

We support MSAA (Microsoft Active Accessibility) and IAccessible2 on Windows. Also we expose MS COM interfaces ISimpleDOM* to provide an access to DOM tree.

- -

IAccessible2 is a set of interfaces that overlay the MSAA (IAccessible) and DOM (ISimpleDOM*) interface support. Any object that supports IAccessible will also support IAccessible2 and possibly any of the other IA2 interfaces.

- -

Linux/Unix platform

- -

We support ATK/AT-SPI interfaces on Linux.

- -

Mac platform

- -

We currently support only a subset of Universal Access. The rest of the Mozilla Universal Access support is in progress.

- -

Accessible Web Specifications

- -

Gecko exposes the number of XML languages including HTML to AT. Refer to accessible web specifications page to learn what and how markup languages are exposed.

- -

AT APIs Implementation Details

- -

Refer to implementation details page to see how Gecko supports interesting AT API. There you will find information how AT API interfaces, roles, states and etc are mapped into Gecko accessibility API and visa versa.

- -

Keyboard User Interface and API

- -

Fortunately, Gecko uses the standard keyboard API's for each supported platform. The Mozilla keyboard shortcuts for content are similar to what is used in other browsers. Here is a list of Firefox keyboard shortcuts.

- -

Test Tools

- -

Here you will find a list of tools to test accessibility Gecko-based applications.

- - - -

Screen Readers

- -

Here's a list of screen readers we are oriented to in the first place.

- - - -

Contacts

- -

Please discuss accessibility issues on the Mozilla Accessibility groups or on the Mozilla Accessibility IRC channel.

diff --git a/files/ru/web/api/devicestorage/index.html b/files/ru/web/api/devicestorage/index.html deleted file mode 100644 index 00c3b20192..0000000000 --- a/files/ru/web/api/devicestorage/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: DeviceStorage -slug: Web/API/DeviceStorage -tags: - - API - - Device Storage - - WebAPI -translation_of: Archive/B2G_OS/API/DeviceStorage ---- -

{{ ApiRef() }}

-

{{ non-standard_header() }}

-

{{ B2GOnlyHeader2('certified') }}

-

Введение

-

DeviceStorage — интерфейс, используемый для доступа к файлам в особом хранилище (или области хранения), доступном на устройстве. Это хранилище, по сути, является файловой системой — хотя оно на самом деле скрывает нижележащую файловую системы.

-

Чтобы получить доступ к хранилищу, необходимо использовать метод {{domxref("window.navigator.getDeviceStorage()","navigator.getDeviceStorage()")}} , возвращающую объекты DeviceStorage. Затем вы сможете использовать методы и свойства этих объектов, чтобы получить доступ к содержимому хранилища.

-

Свойства

-
-
- {{domxref("DeviceStorage.storageName")}} {{readonlyinline}}
-
- Строка, представляющая имя области хранения. Та же, что используется при вызове {{domxref("window.navigator.getDeviceStorage()","getDeviceStorage")}} чтобы получить объект DeviceStorage.
-
- {{domxref("DeviceStorage.default")}} {{readonlyinline}}
-
- Логическое значение, указывающее, назначено ли это хранилище по умолчанию для хранения новых файлов (true) или нет (false).
-
-

Обработчики событий

-
-
- {{domxref("DeviceStorage.onchange")}}
-
- Обрабатывает событие {{event("change")}}. Это событие происходит каждый раз, когда содержимое хранилища меняется.
-
-

Функции

-
-
- {{ domxref("DeviceStorage.add()") }}
-
- Создает файл в области хранения. Имя файла генерируется автоматически.
-
- {{ domxref("DeviceStorage.addNamed()") }}
-
- Создает файл в области хранения. Имя файла задается при вызове функции.
-
- {{ domxref("DeviceStorage.available()") }}
-
- Возвращает available если хранилище доступно для использования и shared если устройство подключено к ПК.
-
- {{ domxref("DeviceStorage.delete()") }}
-
- Удаляет файл из области хранения.
-
- {{ domxref("DeviceStorage.enumerate()") }}
-
- Возвращает список файлов, доступных в области хранения. Полученные файлы доступны только для чтения.
-
- {{ domxref("DeviceStorage.enumerateEditable()") }}
-
- Возвращает список файлов, доступных в области хранения.
-
- {{ domxref("DeviceStorage.freeSpace()") }}
-
- Возвращает количество свободного места, доступного в области хранения.
-
- {{ domxref("DeviceStorage.get()") }}
-
- Возвращает файлы, доступные только для чтения.
-
- {{ domxref("DeviceStorage.getEditable()") }}
-
- Возвращает файлы, доступные для редактирования.
-
- {{ domxref("DeviceStorage.usedSpace()") }}
-
- Возвращает количество занятого места в области хранения.
-
-

Обработчики событий

-

Функции, наследованные от {{domxref("EventTarget")}} интерфейса:

-

{{page("/en-US/docs/Web/API/EventTarget","Methods")}}

-

Спецификация

-

Не является частью какой-либо спецификации.

-

Смотрите также

- diff --git a/files/ru/web/api/fmradio/index.html b/files/ru/web/api/fmradio/index.html deleted file mode 100644 index 0d889f3956..0000000000 --- a/files/ru/web/api/fmradio/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: FMRadio -slug: Web/API/FMRadio -translation_of: Archive/B2G_OS/API/FMRadio ---- -

{{ APIRef("FMRadio API")}}{{ non-standard_header() }}

- -

{{ B2GOnlyHeader2('installed') }}

- -

Summary

- -

WebFM API предоставляет доступ к модулю FM радио устройства. Этот интерфейс поможет Вам включить или выключить FM радио и настроить его на нужную станцию. Это достижимо с помощью параметра {{domxref("window.navigator.mozFMRadio","navigator.mozFMRadio")}}.

- -

Обзор API

- -
interface FMRadio : EventTarget {
-   readonly attribute boolean enabled;
-   readonly attribute boolean antennaAvailable;
-   readonly attribute double frequency;
-   readonly attribute double frequencyUpperBound;
-   readonly attribute double frequencyLowerBound;
-   readonly attribute double channelWidth;
-
-   attribute Function onantennaavailablechange;
-   attribute Function onfrequencychange;
-   attribute Function onenabled;
-   attribute Function ondisabled;
-
-   DOMRequest enable(double frequency);
-   DOMRequest disable();
-   DOMRequest setFrequency(double frequency);
-   DOMRequest seekUp();
-   DOMRequest seekDown();
-   DOMRequest cancelSeek();
-}
- -

Параметры

- -
-
{{domxref("FMRadio.enabled")}}
-
Показывает играет ли радио
-
{{domxref("FMRadio.antennaAvailable")}}
-
Показывает доступна ли антенна
-
{{domxref("FMRadio.frequency")}}
-
Текущая частота радио.
-
{{domxref("FMRadio.frequencyUpperBound")}}
-
Максимальная частота по которой можно найти радиостанцию
-
{{domxref("FMRadio.frequencyLowerBound")}}
-
Минимальная частота по которой можно найти радиостанцию
-
{{domxref("FMRadio.channelWidth")}}
-
Частота текущей радиостанции, в МГц.
-
- -

Event handlers

- -
-
{{domxref("FMRadio.onenabled")}}
-
A handler for the {{event("enabled")}} event; It is triggered when the radio has been turned on
-
{{domxref("FMRadio.ondisabled")}}
-
A handler for the {{event("disabled")}} event; It is triggered when the radio has been turned off
-
{{domxref("FMRadio.onantennaavailablechange")}}
-
A handler for the {{event("antennaavailablechange")}} event; It is triggered when an antenna is plugged or unplugged
-
{{domxref("FMRadio.onfrequencychange")}}
-
A handler for the {{event("frequencychange")}} event; It is triggered whenever the radio frequency is changed
-
- -

Методы

- -
-
{{domxref("FMRadio.enable()")}}
-
Turns on the radio on the given frequency. This function throws if called with no argument. Returns a {{domxref("DOMRequest")}} for the success or error of the operation.
-
{{domxref("FMRadio.disable()")}}
-
Turns the radio off. Returns a {{domxref("DOMRequest")}} which success indicates that the radio has properly been disabled
-
{{domxref("FMRadio.setFrequency()")}}
-
Asynchronously changes the radio frequency. The value has to be between frequencyLowerBound and frequencyUpperBound. Trying to set outside the bounds results in an error.
-
Returns a {{domxref("DOMRequest")}} which success indicates the frequency has properly been changed.
-
{{domxref("FMRadio.seekUp()")}}
-
Asks the radio to find a new frequency (usually greater than the current one). If one is successfully found, a frequencychange event is fired. Returns a {{domxref("DOMRequest")}} which success indicates that the search has started. The search circles back to lower frequencies when the highest frequency has been reached.
-
{{domxref("FMRadio.seekDown()")}}
-
Same as above, but searching in frequencies lower than the current one. The search cirlces back to higher frequencies when the lowest frequency has been reached.
-
{{domxref("FMRadio.cancelSeek()")}}
-
Cancels the radio seek if one was happening. Returns a {{domxref("DOMRequest")}} which success indicates that the frequency search has been cancelled.
-
- -

Спецификация

- -

Ещё нет спецификаций.

- -

See also

- - diff --git a/files/ru/web/api/identitymanager/index.html b/files/ru/web/api/identitymanager/index.html deleted file mode 100644 index 01b4a96364..0000000000 --- a/files/ru/web/api/identitymanager/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: IdentityManager -slug: Web/API/IdentityManager -tags: - - API - - Persona - - Reference -translation_of: Archive/IdentityManager ---- -

{{APIRef("Persona")}}{{non-standard_header}}

- -

The IdentityManager of the  BrowserID protocol exposes the BrowserID API, via {{domxref("navigator.id")}}. This API has gone through several significant revisions. Each generation is listed separately below.

- -

The "Observer" API (Current)

- -

The Observer API introduces much-requested features, such as an improved post-verification experience for first-time users, automatic persistent logins, and easier integration with native applications.

- -
-
{{ domxref("IdentityManager.watch()")}}
-
Registers callbacks to be invoked when a user logs into or out of a website.
-
{{ domxref("IdentityManager.request()")}}
-
Requests a signed identity assertion from the user.
-
{{ domxref("IdentityManager.logout()")}}
-
Logs the user out of a website and prevents the onlogin action from automatically firing on their next visit.
-
- -
-

Users with third-party cookies disabled may experience problems logging in using the Observer API as detailed in issue 2999.

-
- -

The "Callback" API (Current)

- -

The Callback API was introduced in November 2011. It improved upon the initial API by allowing options to be passed to navigator.id.get() and offering experimental support for BrowserID-managed persistent sessions.

- -
-
{{ domxref("IdentityManager.get()")}}
-
Gets the user's BrowserID in a signed assertion.
-
- -

The "VerifiedEmail" API (Deprecated)

- -

The VerifiedEmail API was BrowserID's first API. It was deprecated at the end of 2011.

- -
-
{{ domxref("IdentityManager.getVerifiedEmail()")}} {{ deprecated_inline() }}
-
Gets the user's BrowserID in a signed assertion. This method is deprecated; {{ domxref("navigator.id.get()")}} is backwards compatible and can be used instead.
-
diff --git a/files/ru/web/api/identitymanager/request/index.html b/files/ru/web/api/identitymanager/request/index.html deleted file mode 100644 index 2923f0a359..0000000000 --- a/files/ru/web/api/identitymanager/request/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: navigator.id.request -slug: Web/API/IdentityManager/request -tags: - - API - - BrowserID - - DOM - - Persona - - Безопасность - - Использование - - Настройка - - Справка - - запрос - - метод - - не стандартный - - справка DOM - - справка Gecko DOM -translation_of: Archive/IdentityManager/request ---- -
{{ ApiRef }}
- -

Кратко

- -

Эта функция позволяет использовать Persona для аутентификации пользователей на вебсайте. Она должна вызываться внутри обработки щелчка мыши, к примеру, вы должны вызвать её, когда пользователь щелкнул по кнопке «Войти с помощью Persona».

- -

Когда функция navigator.id.request() вызвана она попросит пользователя выбрать адрес электронной почты, который он желает использовать для входа, а также попросит пройти процедуру аутентификации у поставщика услуг (электронной почты, прим. переводчика), если срок сертификата пользователя истёк. После этого, она создаёт подписанную заявку (assertion), содержащую адрес эл.почты пользователя и передаёт эту заявку функции onlogin, зарегистрированной с помощью {{domxref("navigator.id.watch()")}}.

- -

Эта функция должна использоваться обязательно в связке с  {{domxref("navigator.id.watch()")}}.

- -

Синтаксис

- -
navigator.id.request();
-navigator.id.request({siteName: 'Название сайта', siteLogo: '/logo.png'});
-navigator.id.request({termsOfService: '/tos.html', privacyPolicy: '/privacy.html'});
-
- -

Параметры

- -
-
backgroundColor {{ optional_inline() }}
-
Шестнадцатеричный код цвета для фона диалогового окна. Формат: "#rgb" или "#rrggbb".
-
oncancel {{ optional_inline() }}
-
Функция, которую следует вызвать в случае отказа пользователя предоставить свой идентификатор сайту.
-
privacyPolicy {{ optional_inline() }}
-
Должен передаваться по SSL. Так же должен быть передан параметр termsOfService (Условия Предоставления Услуг).
-
Абсолютный путь или URL до описания политики конфиденциальности веб-сайта. Если этот параметр предоставлен, тогда так же должен быть предоставлен параметр termsOfService. Когда оба эти параметра (termsOfService и privacyPolicy) переданы диалоговое окно входа будет содержать предупреждение для пользователя: "продолжив вход, вы соглашаетесь с политиками использования и конфиденциальности сайта". Так же в диалоговом окне будут размещены ссылки на описания этих политик.
-
returnTo {{ optional_inline() }}
-
Абсолютный путь на который будут отправлены новые пользователи, закончившие процедуру проверки эл.почты в первый раз. Путь должен начинаться с '/'. Этот параметр действует только на тех пользователей, которые проходят сертификацию через запсную Службу Предоставления Идентификаторов от Mozilla (Mozilla's Identity Provider, - прим.). Предоставляемое значение должно указывать реально существующий путь, который может быть использован так же в качестве локации окна – window.location.
-
siteLogo {{ optional_inline() }}
-
Должен передаваться по SSL.
-
Абсолютный путь до изображения, которое будет отображаться в диалоговом окне входа. Путь должен начинаться с '/'. Изображения, превышающие размер 100x100 пикселей будут маштабированы до этого размера.
-
siteName {{ optional_inline() }}
-
Название вашего сайта, которое будет отображаться в диалоговом окне входа в формате простого текста (plain text - прим.). Допустимы символы Юникода и пробельные символы, но не разметка.
-
termsOfService {{ optional_inline() }}
-
Должен передаваться по SSL. Так же должен быть предоставлен параметр privacyPolicy (Политика Конфиденциальности).
-
Абсолютный путь или URL адрес до описания условий предоставления услуг веб-сайта. Если этот параметр указан, тогда так же должен быть указан параметр privacyPolicy.  Когда оба эти параметра (termsOfService и privacyPolicy) переданы диалоговое окно входа будет содержать предупреждение для пользователя: "продолжив вход, вы соглашаетесь с политиками использования и конфиденциальности сайта". Так же в диалоговом окне будут размещены ссылки на описания этих политик.
-
- -

Пример

- -
var signinLink = document.getElementById('signin');
-
-if (signinLink) {
-  signinLink.onclick = function(evt) {
-    // Запрашивает подписанную идентификационную заявку от пользователя.
-    navigator.id.request({
-      siteName: 'Мой Сайт',
-      siteLogo: '/logo.png',
-      termsOfService: '/tos.html',
-      privacyPolicy: '/privacy.html',
-      returnTo: '/welcome.html',
-      oncancel: function() { alert('Пользователь отказался идентифицироваться.'); }
-    });
-  };
-}
- -

Технические описания (Спецификации)

- -

Не включена ни в одно техническое описание.

- -

Также смотрите

- - diff --git a/files/ru/web/api/navigator/getdatastores/index.html b/files/ru/web/api/navigator/getdatastores/index.html deleted file mode 100644 index 5c3b1d7fab..0000000000 --- a/files/ru/web/api/navigator/getdatastores/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Navigator.getDataStores() -slug: Web/API/Navigator/getDataStores -translation_of: Archive/B2G_OS/API/Navigator/getDataStores ---- -
{{APIRef("Data Store API")}} {{ non-standard_header }} {{ B2GOnlyHeader2('certified') }}
- -

Описание

- -

Метод navigator.getDataStores() предоставляющий доступ к списку Data Store API хранилищ данных доступных на устройстве.

- -

Синтаксис

- -
navigator.getDataStores('contacts').then(function(stores) {
-  // сделать что-либо с массивом хранилищ данных в хранилище.
-});
- -

Параметры

- -
-
storeName
-
Имя хранилища данных которое вы хотите вернуть. Возвращается массив, потому что может быть несколько хранилищ данных с таким же именем.
-
- -

Возврат

- -

Объект {{jsxref("Promise")}} который будет связан с массивом объекта {{domxref("DataStore") }}.

- -

Пример

- -
navigator.getDataStores('contacts').then(function(stores) {
-  stores[0].getLength().then(function(storeLength) {
-    if(storeLength == 0) {
-      for(i = 0; i < contactsInit.length; i++) {
-        addContact(stores[0],contactsInit[i]);
-      };
-    } else {
-      var cursor = stores[0].sync();
-      runNextTask(cursor);
-    }
-  });
-});
- -

Спецификации

- -

{{page("/en-US/docs/Web/API/Data_Store_API","Specifications")}}

- -

Совместимость с браузерами

- -

{{page("/en-US/docs/Web/API/Data_Store_API","Browser_compatibility")}}

- -

Смотрите также

- - diff --git a/files/ru/web/api/navigator/id/index.html b/files/ru/web/api/navigator/id/index.html deleted file mode 100644 index ba98e02cf6..0000000000 --- a/files/ru/web/api/navigator/id/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Navigator.id -slug: Web/API/Navigator/id -tags: - - DOM - - Reference - - Référence(2) -translation_of: Archive/Navigator-id ---- -
{{ ApiRef("Persona") }}
- -

Summary

- -

The BrowserID protocol defines a new id property on the {{ domxref ("window.navigator")}} object, through which it exposes the BrowserID API, that is the {{domxref("IdentityManager")}} intreface. This API has gone through several significant revisions. Each generation is listed separately below.

- -

Syntax

- -
var id = navigator.id
- -

 

diff --git a/files/ru/web/api/navigator/mozaudiochannelmanager/index.html b/files/ru/web/api/navigator/mozaudiochannelmanager/index.html deleted file mode 100644 index e8a42e9207..0000000000 --- a/files/ru/web/api/navigator/mozaudiochannelmanager/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Navigator.mozAudioChannelManager -slug: Web/API/Navigator/mozAudioChannelManager -translation_of: Archive/B2G_OS/API/Navigator/mozAudioChannelManager ---- -

{{APIRef("Firefox OS")}}{{Non-standard_header}}

- -

Объект navigator.mozAudioChannelManager предоставляющий доступ к интерфейсу  {{domxref("mozAudioChannelManager")}} который используется для  управления аудио каналами вашего устроства Firefox OS включая настройки эффекта громкости канала, когда кнопки регулировки громкости нажимаются внутри конкретного приложения.

- -

Синтаксис

- -
var mgr = window.navigator.mozAudioChannelManager;
- -

Возвращаемое значение

- -

A {{domxref("mozAudioChannelManager")}} object.

- -

Спецификация

- -

{{page("/en-US/docs/Web/API/mozAudioChannelManager","Specifications")}}

- -

Совместимость с браузерами

- -

{{page("/en-US/docs/Web/API/mozAudioChannelManager","Browser_compatibility")}}

- -

Смотрите также

- - diff --git a/files/ru/web/api/navigator/mozcamera/index.html b/files/ru/web/api/navigator/mozcamera/index.html deleted file mode 100644 index 620fba2e0e..0000000000 --- a/files/ru/web/api/navigator/mozcamera/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Navigator.mozCamera -slug: Web/API/Navigator/mozCamera -translation_of: Archive/B2G_OS/API/Navigator/mozCamera ---- -

{{APIRef("Firefox OS")}}

- -

{{ non-standard_header() }}

- -

{{B2GOnlyHeader2('privileged')}}

- -

Резюме

- -

Возвращает объект {{ domxref("CameraManager") }} который вы можите использовать для доступа к камере доступной на устройстве пользователя.

- -

Синтаксис

- -
var camera = window.navigator.mozCamera;
-
- -

Значение

- -

navigator.mozCamera это объект {{domxref("CameraManager")}} который вы можете использовать для доступа к камере доступной на устройстве.

- -

Спецификация

- -

Не является еще частю какой-либо спецификации; Оно, вероятно, будет заменено на WebRTC, когда оно получит более широкую поддержку на мобильных устройствах.

- -

Права доступа

- -

До Firefox OS 1.4,  API камеры было сертифицированным API, недоступным для сторонних приложений. С Firefox OS 2.0 и далее,  Уровень доступа был понижен до привелигированного, так что теперь доступно для разработчиков сторонних приложений.

- -
"permissions": {
-  "camera": {
-    "description": "Required for accessing cameras on the device."
-  }
-}
- -

Смотрите также

- - diff --git a/files/ru/web/api/navigator/mozl10n/index.html b/files/ru/web/api/navigator/mozl10n/index.html deleted file mode 100644 index 590d3238cd..0000000000 --- a/files/ru/web/api/navigator/mozl10n/index.html +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: Navigator.mozL10n -slug: Web/API/Navigator/mozL10n -tags: - - API - - Firefox OS - - Localization - - Reference - - Référence(2) - - Локализация - - Справка - - Справка(2) -translation_of: Archive/B2G_OS/API/Navigator/mozL10n ---- -

{{APIRef("Firefox OS")}}{{ non-standard_header() }}

- -

navigator.mozL10n возвращает объект {{ domxref("L10n") }}, который вы можете использовать для доступа к ресурсам локализации и реагировать на события локализации.

- -

Синтаксис

- -
var l10n = navigator.mozL10n;
-
- -

Значение

- -

navigator.mozL10n возвращает объект{{domxref("L10n")}}.

- -

Спецификация

- -

Не имеет спецификации. Заметим, что в будущем этот API будет заменен на L20n.

- -

Смотри также

- - diff --git a/files/ru/web/api/navigator/moznfc/index.html b/files/ru/web/api/navigator/moznfc/index.html deleted file mode 100644 index 8e21ea296b..0000000000 --- a/files/ru/web/api/navigator/moznfc/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Navigator.mozNfc -slug: Web/API/Navigator/mozNfc -translation_of: Archive/B2G_OS/API/Navigator/mozNfc ---- -

{{APIRef("Firefox OS")}}{{ non-standard_header() }}

- -

Описание

- -

Свойство mozNfc возвращает объект {{ domxref("MozNFC") }} который может быть использован для доступа к функциональности Firefox OS's NFC: Near Field Communication (NFC)  это радио технология малой дальности, используемая для обмена данными и тегами между мобильными устройствами прижатыми друг к другу или находящимися близко друг к другу.

- -

Для получения детальной иформации о NFC, прочтите Использование NFC API и изучите NFC справку.

- -

Синтаксис

- -
var nfc = navigator.mozNfc;
-
- -

Возвращаемое значение

- -

navigator.mozNfc возвращает объект {{ domxref("MozNFC") }}.

- -

Совместимость с браузерами

- -

{{page("/en-US/docs/Web/API/NFC_API","Browser_compatibility")}}

- -

Спецификация

- -

{{page("/en-US/docs/Web/API/NFC_API","Specification")}}

- -

Смотрите также

- - diff --git a/files/ru/web/api/webfm_api/index.html b/files/ru/web/api/webfm_api/index.html deleted file mode 100644 index 11727674af..0000000000 --- a/files/ru/web/api/webfm_api/index.html +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: WebFM API -slug: Web/API/WebFM_API -tags: - - WebFMAPI -translation_of: Archive/B2G_OS/API/WebFM_API ---- -

{{ non-standard_header() }}

- -

{{ B2GOnlyHeader2('installed') }}

- -

Summary

- -

The WebFM API provides access to the device FM radio. It allows turning the radio on/off and switching among radio stations. This API is available through the {{domxref("window.navigator.mozFMRadio","navigator.mozFMRadio")}} property which is a {{domxref("FMRadio")}} object.

- -

Включение и выключение радио

- -

Для того чтобы включить радио используйте метод {{domxref("FMRadio.enable()")}}, для выключения {{domxref("FMRadio.disable()")}}.

- -

Перед включением радио следует проверить доступность антены, так как без нее встроенный радиомодуль не в состоянии поймать какую либо станцию. Информация о доступности антенны находится в свойстве {{domxref("FMRadio.antennaAvailable")}}. Как правило, в мобильных устройствах роль антены выполняют наушники (проводная гарнитура). Каждый раз когда пользователь подсоединяет или отсоединяет проводную гарнитуру WebFM API вызывает событие {{event("antennaavailablechange")}}.

- -

To turn the radio on it's necessary to provide a frequency to listen. That frequency (in MHz) is a number pass to the {{domxref("FMRadio.enable()")}} method.

- -
// Частота радиостанции в MHz
-var frequency = 99.1;
-var radio = navigator.mozFMRadio;
-
-if (radio.antennaAvailable) {
-  radio.enable(frequency);
-} else {
-  alert("Вам необходимо подсоединить гарнитуру");
-}
-
-radio.addEventListener('antennaavailablechange', function () {
-  if (radio.antennaAvailable) {
-    radio.enable(frequency);
-  } else {
-    radio.disable();
-  }
-})
-
- -
-

Note: The audio is output through the normal audio channel available on the device.

-
- -

Switching among frequency

- -

Switching from on frequency to another can be done manually or automatically. In any case, the current radio frequency listened to by the built-in radio is always available with the {{domxref("FMRadio.frequency")}} property. That property is number representing the frequency in MHz.

- -

Manual switch

- -

The {{domxref("FMRadio.setFrequency()")}} method must be used to set a new frequency to listen. However, there are some constraints about the value that can be set. The method will return a {{domxref("DOMRequest")}} object to handle the success or error of the method call. The frequency must fulfill the following requirements:

- - - -
var change = radio.setFrequency(frequency);
-
-change.onerror = function () {
-  var min = radio.frequencyLowerBound;
-  var max = radio.frequencyUpperBound;
-  console.warn('The frequency must be within the range [' + min + ',' + max + ']');
-}
-
-change.onsuccess = function () {
-  console.log('The frequency has been set to ' + radio.frequency);
-}
-
- -

Автоматический поиск

- -

WebFM API предоставляет удобный способ автоматического поиска радиоканалов. Для восходящего поиска используйте метод {{domxref("FMRadio.seekUp()")}}, а для низходящего, метод {{domxref("FMRadio.seekDown()")}}.

- -

The WebFM API also provides a convinient way to seek radio channels automatically. To that end, we can use the {{domxref("FMRadio.seekUp()")}} (to find a radio channel on a higher frequency than the current one) and {{domxref("FMRadio.seekDown()")}} method. The former is used to find a radio channel with a higher frequency than the current one, and the latter for a radio channel with a lower frequency. Those methods return a {{domxref("DOMRequest")}} object to handle the success or error of each method call.

- -

Both methods will circle back to higher or lower frequency once they reach the {{domxref("FMRadio.frequencyLowerBound","frequencyLowerBound")}} or {{domxref("FMRadio.frequencyUpperBound","frequencyUpperBound")}} values. When they find a new radio channel, they change the current frequency and fire a {{event("frequencychange")}} event.

- -

It's not possible to seek twice at the same time (e.g. it's not possible to seek up and down at the same time), trying to do so, will result in an error. But if necessary it's possible to stop seeking by calling the {{domxref("FMRadio.cancelSeek()")}} method. This method will also return a {{domxref("DOMRequest")}} object.

- -
var radio   = navigator.mozFMRadio;
-var seeking = false;
-var UP      = document.querySelector("button.up");
-var DOWN    = document.querySelector("button.down");
-
-// When the frequency change, the seek
-// functions automatically stop to seek.
-radio.onfrequencychange = function () {
-  seeking = false;
-}
-
-function seek(direction) {
-  var cancel, search;
-
-  // If the radio is already seeking
-  // we will cancel the current search.
-  if (seeking) {
-    var cancel = radio.cancelSeek();
-    cancel.onsuccess = function () {
-      seeking = false;
-
-      // Once the radio no longer seek,
-      // we can try to seek as expected
-      seek(direction);
-    }
-
-  // Let's seek up
-  } else if (direction === 'up') {
-    // Just to be sure that the radio is turned on
-    if (!radio.enabled) {
-      radio.enable(radio.frequencyLowerBound);
-    }
-    search = radio.seekUp();
-
-  // Let's seek up
-  } else if (direction === 'down' {
-    // Just to be sure that the radio is turned on
-    if (!radio.enabled) {
-      radio.enable(radio.frequencyUpperBound);
-    }
-    search = radio.seekDown();
-  }
-
-  if (search) {
-    search.onsuccess = function () {
-      // Ok, we are seeking now.
-      seeking = true;
-    };
-    search.onerror = function () {
-      // Something goes wrong... ok, let's try again.
-      seek(direction);
-    }
-  }
-}
-
-UP.addEventListener('click', function () {
-  seek('up');
-});
-
-DOWN.addEventListener('click', function () {
-  seek('down');
-});
-
- -

Specification

- -

Not part of any specification.

- -

See also

- - diff --git a/files/ru/web/css/-moz-binding/index.html b/files/ru/web/css/-moz-binding/index.html deleted file mode 100644 index e9c8b29c44..0000000000 --- a/files/ru/web/css/-moz-binding/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: '-moz-binding' -slug: Web/CSS/-moz-binding -translation_of: Archive/Web/CSS/-moz-binding ---- -
{{CSSRef}}{{Non-standard_Header}}{{Deprecated_Header(57)}}
- -

The -moz-binding CSS property is used by Mozilla-based applications to attach an XBL binding to a DOM element.

- -

{{CSSInfo}}

- -

Syntax

- -
/* <url> value */
--moz-binding: url(http://www.example.org/xbl/htmlBindings.xml#checkbox);
-
-/* Global values */
--moz-binding: inherited;
--moz-binding: initial;
--moz-binding: unset;
-
- -

Values

- -
-
{{CSSxRef("<url>")}}
-
The URL for the XBL binding (including the fragment identifier).
-
none
-
No XBL binding is applied to the element.
-
- -

Formal syntax

- -
{{CSSSyntax}}
- -

Example

- -
.exampleone {
-  -moz-binding: url(http://www.example.org/xbl/htmlBindings.xml#radiobutton);
-}
- -

Specifications

- -

Not part of any specification.

- -

Browser compatibility

- -
-

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefoxIEOperaSafari
Basic support {{Deprecated_Inline}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureWebView AndroidChrome AndroidEdge MobileFirefox AndroidOpera AndroidSafari iOSSamsung Internet Android
Basic support {{Deprecated_Inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

1. XBL is deprecated and being removed (See {{bug(1397874)}}).

-
- -

See also

- - diff --git a/files/ru/web/events/dommodaldialogclosed/index.html b/files/ru/web/events/dommodaldialogclosed/index.html deleted file mode 100644 index 67b480544b..0000000000 --- a/files/ru/web/events/dommodaldialogclosed/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: DOMModalDialogClosed -slug: Web/Events/DOMModalDialogClosed -translation_of: Archive/Add-ons/Events/DOMModalDialogClosed ---- -

The DOMModalDialogClosed event is executed when a modal dialog has been closed.

- -

General info

- -
-
Specification
-
Addons specific
-
Interface
-
Event
-
Bubbles
-
Yes
-
Cancelable
-
Yes
-
Target
-
window, browser
-
Default Action
-
None
-
- -

Properties

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
- -

See also

- - diff --git a/files/ru/web/events/domsubtreemodified/index.html b/files/ru/web/events/domsubtreemodified/index.html deleted file mode 100644 index dfd00fe94d..0000000000 --- a/files/ru/web/events/domsubtreemodified/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: DOMSubtreeModified -slug: Web/Events/DOMSubtreeModified -tags: - - DOMSubtreeModified -translation_of: Archive/Events/DOMSubtreeModified ---- -

Пример

- -

Следующий код отображает время последнего изменения DOM в строке заголовка страницы.

- -
-

Это событие устарело в пользу  Mutation Observer API

-
- -
Будьте очень осторожны с этим событием, легко вызвать бесконечный цикл, если вы решите изменить DOM внутри обработчика событий.
- -
document.body.addEventListener('DOMSubtreeModified', function () {
-  document.title = 'DOM Изменен в ' + new Date();
-}, false);
-
diff --git a/files/ru/web/javascript/guide/liveconnect_overview/index.html b/files/ru/web/javascript/guide/liveconnect_overview/index.html deleted file mode 100644 index baf6f2577c..0000000000 --- a/files/ru/web/javascript/guide/liveconnect_overview/index.html +++ /dev/null @@ -1,795 +0,0 @@ ---- -title: LiveConnect Overview -slug: Web/JavaScript/Guide/LiveConnect_Overview -translation_of: Archive/Web/LiveConnect/LiveConnect_Overview ---- -

Эта глава описывает технолонию LiveConnect которая позволяет Java и JavaScript взаимодейстовать между собой. В этой главе полагается что вы имеет представление о языке программирования Java.

- -

Working with Wrappers

- -

В JavaScript, обертка это объект s an object of the target language data type that encloses an object of the source language. When programming in JavaScript, you can use a wrapper object to access methods and fields of the Java object; calling a method or accessing a property on the wrapper results in a call on the Java object. On the Java side, JavaScript objects are wrapped in an instance of the class netscape.javascript.JSObject and passed to Java.

- -

When a JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type JSObject; when a JSObject is sent from Java to JavaScript, the runtime engine unwraps it to its original JavaScript object type. The JSObject class provides an interface for invoking JavaScript methods and examining JavaScript properties.

- -

JavaScript to Java Communication

- -

When you refer to a Java package or class, or work with a Java object or array, you use one of the special LiveConnect objects. All JavaScript access to Java takes place with these objects, which are summarized in the following table.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 9.1 The LiveConnect Objects
ObjectDescription
JavaArrayA wrapped Java array, accessed from within JavaScript code.
JavaClassA JavaScript reference to a Java class.
JavaObjectA wrapped Java object, accessed from within JavaScript code.
JavaPackageA JavaScript reference to a Java package.
- -

Note: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See Data Type Conversion for complete information.

- -

In some ways, the existence of the LiveConnect objects is transparent, because you interact with Java in a fairly intuitive way. For example, you can create a Java String object and assign it to the JavaScript variable myString by using the new operator with the Java constructor, as follows:

- -
var myString = new java.lang.String("Hello world");
-
- -

In the previous example, the variable myString is a JavaObject because it holds an instance of the Java object String. As a JavaObject, myString has access to the public instance methods of java.lang.String and its superclass, java.lang.Object. These Java methods are available in JavaScript as methods of the JavaObject, and you can call them as follows:

- -
myString.length(); // returns 11
-
- -

Static members can be called directly on the JavaClass object.

- -
alert(java.lang.Integer.MAX_VALUE); //alerts 2147483647
-
- -

The Packages Object

- -

If a Java class is not part of the java, sun, or netscape packages, you access it with the Packages object. For example, suppose the Redwood corporation uses a Java package called redwood to contain various Java classes that it implements. To create an instance of the HelloWorld class in redwood, you access the constructor of the class as follows:

- -
var red = new Packages.redwood.HelloWorld();
-
- -

You can also access classes in the default package (that is, classes that don't explicitly name a package). For example, if the HelloWorld class is directly in the CLASSPATH and not in a package, you can access it as follows:

- -
var red = new Packages.HelloWorld();
-
- -

The LiveConnect java, sun, and netscape objects provide shortcuts for commonly used Java packages. For example, you can use the following:

- -
var myString = new java.lang.String("Hello world");
-
- -

instead of the longer version:

- -
var myString = new Packages.java.lang.String("Hello world");
-
- -

Working with Java Arrays

- -

When any Java method creates an array and you reference that array in JavaScript, you are working with a JavaArray. For example, the following code creates the JavaArray x with ten elements of type int:

- -
var x = java.lang.reflect.Array.newInstance(java.lang.Integer, 10);
-
- -

Like the JavaScript Array object, JavaArray has a length property which returns the number of elements in the array. Unlike Array.length, JavaArray.length is a read-only property, because the number of elements in a Java array are fixed at the time of creation.

- -

Package and Class References

- -

Simple references to Java packages and classes from JavaScript create the JavaPackage and JavaClass objects. In the earlier example about the Redwood corporation, for example, the reference Packages.redwood is a JavaPackage object. Similarly, a reference such as java.lang.String is a JavaClass object.

- -

Most of the time, you don't have to worry about the JavaPackage and JavaClass objects—you just work with Java packages and classes, and LiveConnect creates these objects transparently. There are cases where LiveConnect will fail to load a class, and you will need to manually load it like this:

- -
var Widgetry = java.lang.Thread.currentThread().getContextClassLoader().loadClass("org.mywidgets.Widgetry");
-
- -

In JavaScript 1.3 and earlier, JavaClass objects are not automatically converted to instances of java.lang.Class when you pass them as parameters to Java methods—you must create a wrapper around an instance of java.lang.Class. In the following example, the forName method creates a wrapper object theClass, which is then passed to the newInstance method to create an array.

- -
// JavaScript 1.3
-var theClass = java.lang.Class.forName("java.lang.String");
-var theArray = java.lang.reflect.Array.newInstance(theClass, 5);
-
- -

In JavaScript 1.4 and later, you can pass a JavaClass object directly to a method, as shown in the following example:

- -
// JavaScript 1.4
-var theArray = java.lang.reflect.Array.newInstance(java.lang.String, 5);
-
- -

Arguments of Type char

- -

In JavaScript 1.4 and later, you can pass a one-character string to a Java method which requires an argument of type char. For example, you can pass the string "H" to the Character constructor as follows:

- -
var c = new java.lang.Character("H");
-
- -

In JavaScript 1.3 and earlier, you must pass such methods an integer which corresponds to the Unicode value of the character. For example, the following code also assigns the value "H" to the variable c:

- -
var c = new java.lang.Character(72);
-
- -

Handling Java Exceptions in JavaScript

- -

When Java code fails at run time, it throws an exception. If your JavaScript code accesses a Java data member or method and fails, the Java exception is passed on to JavaScript for you to handle. Beginning with JavaScript 1.4, you can catch this exception in a try...catch statement. (Although this functionality (along with some others) had been broken in Gecko 1.9 (see {{ bug("391642") }}) as the Mozilla-specific LiveConnect code had not been maintained inside Mozilla, with Java 6 update 11 and 12 building support for reliance on Mozilla's implementation of the generic (and cross-browser) NPAPI plugin code, this has again been fixed.)

- -

For example, suppose you are using the Java forName method to assign the name of a Java class to a variable called theClass. The forName method throws an exception if the value you pass it does not evaluate to the name of a Java class. Place the forName assignment statement in a try block to handle the exception, as follows:

- -
function getClass(javaClassName) {
-   try {
-      var theClass = java.lang.Class.forName(javaClassName);
-   } catch (e) {
-      return ("The Java exception is " + e);
-   }
-   return theClass;
-}
-
- -

In this example, if javaClassName evaluates to a legal class name, such as "java.lang.String", the assignment succeeds. If javaClassName evaluates to an invalid class name, such as "String", the getClass function catches the exception and returns something similar to the following:

- -
The Java exception is java.lang.ClassNotFoundException: String
-
- -

For specialized handling based on the exception type, use the instanceof operator:

- -
try {
-  // ...
-} catch (e) {
-  if (e instanceof java.io.FileNotFound) {
-     // handling for FileNotFound
-  } else {
-    throw e;
-  }
-}
-
- -

See Exception Handling Statements for more information about JavaScript exceptions.

- -

Java to JavaScript Communication

- -

If you want to use JavaScript objects in Java, you must import the netscape.javascript package into your Java file. This package defines the following classes:

- - - -

See the JavaScript Reference for more information about these classes.

- -

Locating the LiveConnect classes

- -

In older versions of the Netscape browser, these classes were distributed along with the browser. Starting with JavaScript 1.2, these classes are delivered in a .jar file; in previous versions of JavaScript, these classes are delivered in a .zip file. For example, with Netscape Navigator 4 for Windows NT, the classes are delivered in the java40.jar file in the Program\Java\Classes directory beneath the Navigator directory.

- -

More recently, the classes have been distributed with Sun's Java Runtime; initially in the file "jaws.jar" in the "jre/lib" directory of the runtime distribution (for JRE 1.3), then in "plugin.jar" in the same location (JRE 1.4 and up).

- -

Using the LiveConnect classes with the JDK

- -

To access the LiveConnect classes, place the .jar or .zip file in the CLASSPATH of the JDK compiler in either of the following ways:

- - - -

You can specify an environment variable in Windows NT by double-clicking the System icon in the Control Panel and creating a user environment variable called CLASSPATH with a value similar to the following:

- -
C:\Program Files\Java\jre1.4.1\lib\plugin.jar
-
- -

See the Sun JDK documentation for more information about CLASSPATH.

- -

Note: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See Data Type Conversions for complete information.

- -

Using the LiveConnect Classes

- -

All JavaScript objects appear within Java code as instances of netscape.javascript.JSObject. When you call a method in your Java code, you can pass it a JavaScript object as one of its argument. To do so, you must define the corresponding formal parameter of the method to be of type JSObject.

- -

Also, any time you use JavaScript objects in your Java code, you should put the call to the JavaScript object inside a try...catch statement which handles exceptions of type netscape.javascript.JSException. This allows your Java code to handle errors in JavaScript code execution which appear in Java as exceptions of type JSException.

- -

Accessing JavaScript with JSObject

- -

For example, suppose you are working with the Java class called JavaDog. As shown in the following code, the JavaDog constructor takes the JavaScript object jsDog, which is defined as type JSObject, as an argument:

- -
import netscape.javascript.*;
-
-public class JavaDog{
-    public String dogBreed;
-    public String dogColor;
-    public String dogSex;
-
-    // define the class constructor
-    public JavaDog(JSObject jsDog){
-        // use try...catch to handle JSExceptions here
-        this.dogBreed = (String)jsDog.getMember("breed");
-        this.dogColor = (String)jsDog.getMember("color");
-        this.dogSex = (String)jsDog.getMember("sex");
-    }
-}
-
- -

Notice that the getMember method of JSObject is used to access the properties of the JavaScript object. The previous example uses getMember to assign the value of the JavaScript property jsDog.breed to the Java data member JavaDog.dogBreed.

- -

Note: A more realistic example would place the call to getMember inside a try...catch statement to handle errors of type JSException. See Handling JavaScript Exceptions in Java for more information.

- -

To get a better sense of how getMember works, look at the definition of the custom JavaScript object Dog:

- -
function Dog(breed,color,sex){
-   this.breed = breed;
-   this.color = color;
-   this.sex = sex;
-}
-
- -

You can create a JavaScript instance of Dog called gabby as follows:

- -
var gabby = new Dog("lab", "chocolate", "female");
-
- -

If you evaluate gabby.color, you can see that it has the value "chocolate". Now suppose you create an instance of JavaDog in your JavaScript code by passing the gabby object to the constructor as follows:

- -
var javaDog = new Packages.JavaDog(gabby);
-
- -

If you evaluate javaDog.dogColor, you can see that it also has the value "chocolate", because the getMember method in the Java constructor assigns dogColor the value of gabby.color.

- -

Handling JavaScript Exceptions in Java

- -

When JavaScript code called from Java fails at run time, it throws an exception. If you are calling the JavaScript code from Java, you can catch this exception in a try...catch statement. The JavaScript exception is available to your Java code as an instance of netscape.javascript.JSException.

- -

JSException is a Java wrapper around any exception type thrown by JavaScript, similar to the way that instances of JSObject are wrappers for JavaScript objects. Use JSException when you are evaluating JavaScript code in Java.

- -

When you are evaluating JavaScript code in Java, the following situations can cause run-time errors:

- - - -

For example, suppose the Java object eTest evaluates the string jsCode that you pass to it. You can respond to either type of run-time error the evaluation causes by implementing an exception handler such as the following:

- -
import netscape.javascript.JSObject;
-import netscape.javascript.JSException;
-
-public class eTest {
-    public static Object doit(JSObject obj, String jsCode) {
-        try {
-            obj.eval(jsCode);
-        } catch (JSException e) {
-            if (e.getWrappedException() == null)
-                return e;
-            return e.getWrappedException();
-        }
-        return null;
-    }
-}
-
- -

In this example, the code in the try block attempts to evaluate the string jsCode that you pass to it. Let's say you pass the string "myFunction()" as the value of jsCode. If myFunction is not defined as a JavaScript function, the JavaScript interpreter cannot evaluate jsCode. The interpreter generates an error message, the Java handler catches the message, and the doit method returns an instance of netscape.javascript.JSException.

- -

However, suppose myFunction is defined in JavaScript as follows:

- -
function myFunction() {
-   try {
-      if (theCondition == true) {
-         return "Everything's ok";
-      } else {
-         throw "JavaScript error occurred";
-      }
-   } catch (e) {
-      if (canHandle == true) {
-         handleIt();
-      } else {
-         throw e;
-      }
-   }
-}
-
- -

If theCondition is false, the function throws an exception. The exception is caught in the JavaScript code, and if canHandle is true, JavaScript handles it. If canHandle is false, the exception is rethrown, the Java handler catches it, and the doit method returns a Java string:

- -
JavaScript error occurred
-
- -

See Exception Handling Statements for complete information about JavaScript exceptions.

- -

Backward Compatibility

- -

In JavaScript 1.3 and earlier versions, the JSException class had three public constructors which optionally took a string argument, specifying the detail message or other information for the exception. The getWrappedException method was not available.

- -

Use a try...catch statement such as the following to handle LiveConnect exceptions in JavaScript 1.3 and earlier versions:

- -
try {
-   global.eval("foo.bar = 999;");
-} catch (Exception e) {
-   if (e instanceof JSException) {
-      jsCodeFailed();
-   } else {
-      otherCodeFailed();
-   }
-}
-
- -

In this example, the eval statement fails if foo is not defined. The catch block executes the jsCodeFailed method if the eval statement in the try block throws a JSException; the otherCodeFailed method executes if the try block throws any other error.

- -

Data Type Conversions

- -

Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. These conversions are described in the following sections:

- - - -

JavaScript to Java Conversions

- -

When you call a Java method and pass it parameters from JavaScript, the data types of the parameters you pass in are converted according to the rules described in the following sections:

- - - -

The return values of methods of netscape.javascript.JSObject are always converted to instances of java.lang.Object. The rules for converting these return values are also described in these sections.

- -

For example, if JSObject.eval returns a JavaScript number, you can find the rules for converting this number to an instance of java.lang.Object in Number Values.

- -

Number Values

- -

When you pass JavaScript number types as parameters to Java methods, Java converts the values according to the rules described in the following table:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Java parameter typeConversion rules
double -
    -
  • The exact value is transferred to Java without rounding and without a loss of magnitude or sign.
  • -
  • NaN is converted to NaN.
  • -
-
java.lang.Double
- java.lang.Object
A new instance of java.lang.Double is created, and the exact value is transferred to Java without rounding and without a loss of magnitude or sign.
float -
    -
  • Values are rounded to float precision.
  • -
  • Values which are too large or small to be represented are rounded to +infinity or -infinity.
  • -
  • NaN is converted to NaN.
  • -
-
byte -

char
- int
- long

- short
-
    -
  • Values are rounded using round-to-negative-infinity mode.
  • -
  • Values which are too large or small to be represented result in a run-time error.
  • -
  • NaN can not be converted and results in a run-time error.
  • -
-
java.lang.StringValues are converted to strings. For example: -
    -
  • 237 becomes "237"
  • -
-
boolean -
    -
  • 0 and NaN values are converted to false.
  • -
  • Other values are converted to true.
  • -
-
- -

When a JavaScript number is passed as a parameter to a Java method which expects an instance of java.lang.String, the number is converted to a string. Use the equals() method to compare the result of this conversion with other string values.

- -

Boolean Values

- -

When you pass JavaScript Boolean types as parameters to Java methods, Java converts the values according to the rules described in the following table:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Java parameter typeConversion rules
booleanAll values are converted directly to the Java equivalents.
java.lang.Boolean
- java.lang.Object
A new instance of java.lang.Boolean is created. Each parameter creates a new instance, not one instance with the same primitive value.
java.lang.StringValues are converted to strings. For example: -
    -
  • true becomes "true"
  • -
  • false becomes "false"
  • -
-
byte -

char
- double
- float
- int
- long

- short
-
    -
  • true becomes 1
  • -
  • false becomes 0
  • -
-
- -

When a JavaScript Boolean is passed as a parameter to a Java method which expects an instance of java.lang.String, the Boolean is converted to a string. Use the == operator to compare the result of this conversion with other string values.

- -

String Values

- -

When you pass JavaScript string types as parameters to Java methods, Java converts the values according to the rules described in the following table:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Java parameter typeConversion rules
java.lang.String
- java.lang.Object
JavaScript 1.4: -
    -
  • A JavaScript string is converted to an instance of java.lang.String with a Unicode value.
  • -
- -

JavaScript 1.3 and earlier:

- -
    -
  • A JavaScript string is converted to an instance of java.lang.String with an ASCII value.
  • -
-
byte -

double
- float
- int
- long

- short
All values are converted to numbers as described in ECMA-262. The JavaScript string value is converted to a number according to the rules described in ECMA-262.
charJavaScript 1.4: -
    -
  • One-character strings are converted to Unicode characters.
  • -
  • All other values are converted to numbers.
  • -
- -

JavaScript 1.3 and earlier:

- -
    -
  • All values are converted to numbers.
  • -
-
boolean -
    -
  • The empty string becomes false.
  • -
  • All other values become true.
  • -
-
- -

Undefined Values

- -

When you pass undefined JavaScript values as parameters to Java methods, Java converts the values according to the rules described in the following table:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Java parameter typeConversion rules
java.lang.String
- java.lang.Object
The value is converted to an instance of java.lang.String whose value is the string "undefined".
booleanThe value becomes false.
double
- float
The value becomes NaN.
byte -

char
- int
- long

- short
The value becomes 0.
- -

The undefined value conversion is possible in JavaScript 1.3 and later versions only. Earlier versions of JavaScript do not support undefined values.

- -

When a JavaScript undefined value is passed as a parameter to a Java method which expects an instance of java.lang.String, the undefined value is converted to a string. Use the == operator to compare the result of this conversion with other string values.

- -

Null Values

- -

When you pass null JavaScript values as parameters to Java methods, Java converts the values according to the rules described in the following table:

- - - - - - - - - - - - - - - - - - - - - - -
Java parameter typeConversion rules
Any class
- Any interface type
The value becomes null.
byte -

char
- double
- float
- int
- long

- short
The value becomes 0.
booleanThe value becomes false.
- -

JavaArray and JavaObject objects

- -

In most situations, when you pass a JavaScript JavaArray or JavaObject as a parameter to a Java method, Java simply unwraps the object; in a few situations, the object is coerced into another data type according to the rules described in the following table:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Java parameter typeConversion rules
Any interface or class that is assignment-compatible with the unwrapped object.The object is unwrapped.
java.lang.StringThe object is unwrapped, the toString method of the unwrapped Java object is called, and the result is returned as a new instance of java.lang.String.
byte -

char
- double
- float
- int
- long

- short
The object is unwrapped, and either of the following situations occur: -
    -
  • If the unwrapped Java object has a doubleValue method, the JavaArray or JavaObject is converted to the value returned by this method.
  • -
  • If the unwrapped Java object does not have a doubleValue method, an error occurs.
  • -
-
booleanIn JavaScript 1.3 and later versions, the object is unwrapped and either of the following situations occur: -
    -
  • If the object is null, it is converted to false.
  • -
  • If the object has any other value, it is converted to true.
  • -
- -

In JavaScript 1.2 and earlier versions, the object is unwrapped and either of the following situations occur:

- -
    -
  • If the unwrapped object has a booleanValue method, the source object is converted to the return value.
  • -
  • If the object does not have a booleanValue method, the conversion fails.
  • -
-
- -

An interface or class is assignment-compatible with an unwrapped object if the unwrapped object is an instance of the Java parameter type. That is, the following statement must return true:

- -
unwrappedObject instanceof parameterType;
-
- -

JavaClass objects

- -

When you pass a JavaScript JavaClass object as a parameter to a Java method, Java converts the object according to the rules described in the following table:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Java parameter typeConversion rules
java.lang.ClassThe object is unwrapped.
netscape.javascript.JSObject
- java.lang.Object
The JavaClass object is wrapped in a new instance of netscape.javascript.JSObject.
java.lang.StringThe object is unwrapped, the toString method of the unwrapped Java object is called, and the result is returned as a new instance of java.lang.String.
booleanIn JavaScript 1.3 and later versions, the object is unwrapped and either of the following situations occur: -
    -
  • If the object is null, it is converted to false.
  • -
  • If the object has any other value, it is converted to true.
  • -
- -

In JavaScript 1.2 and earlier versions, the object is unwrapped and either of the following situations occur:

- -
    -
  • If the unwrapped object has a booleanValue method, the source object is converted to the return value.
  • -
  • If the object does not have a booleanValue method, the conversion fails.
  • -
-
- -

Other JavaScript objects

- -

When you pass any other JavaScript object as a parameter to a Java method, Java converts the object according to the rules described in the following table:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Java parameter typeConversion rules
netscape.javascript.JSObject
- java.lang.Object
The object is wrapped in a new instance of netscape.javascript.JSObject.
java.lang.StringThe object is unwrapped, the toString method of the unwrapped object is called, and the result is returned as a new instance of java.lang.String.
byte -

char
- double
- float
- int
- long

- short
The object is converted to a value using the logic of the ToPrimitive operator described in ECMA-262. The PreferredType hint used with this operator is Number.
booleanIn JavaScript 1.3 and later versions, the object is unwrapped and either of the following situations occur: -
    -
  • If the object is null, it is converted to false.
  • -
  • If the object has any other value, it is converted to true.
  • -
- -

In JavaScript 1.2 and earlier versions, the object is unwrapped and either of the following situations occur:

- -
    -
  • If the unwrapped object has a booleanValue method, the source object is converted to the return value.
  • -
  • If the object does not have a booleanValue method, the conversion fails.
  • -
-
- -

Java to JavaScript Conversions

- -

Values passed from Java to JavaScript are converted as follows:

- - - -

Note that instances of java.lang.Double and java.lang.Integer are converted to JavaScript objects, not to JavaScript numbers. Similarly, instances of java.lang.String are also converted to JavaScript objects, not to JavaScript strings.

- -

Java String objects also correspond to JavaScript wrappers. If you call a JavaScript method that requires a JavaScript string and pass it this wrapper, you'll get an error. Instead, convert the wrapper to a JavaScript string by appending the empty string to it, as shown here:

- -
var JavaString = JavaObj.methodThatReturnsAString();
-var JavaScriptString = JavaString + "";
diff --git a/files/ru/web/javascript/new_in_javascript/1.5/index.html b/files/ru/web/javascript/new_in_javascript/1.5/index.html deleted file mode 100644 index a27746c51b..0000000000 --- a/files/ru/web/javascript/new_in_javascript/1.5/index.html +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Новое в JavaScript 1.5 -slug: Web/JavaScript/New_in_JavaScript/1.5 -translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.5 ---- -
{{jsSidebar("New_in_JS")}}
- -

Следующий список описывает изменения в JavaScript 1.5. Эта версия была включена в Netscape Navigator 6.0, дата релиза которого – 14 ноября 2000 года. Также Javascript 1.5 использовался в более поздних версиях Netscape Navigator, а также Firefox 1.0.  JavaScript 1.5 соответствует JScript версии 5.5 используемой в Internet Explorer 5.5, который был представлен в июле 2000. Соответствующая версия стандарта ECMA – ECMA-262 третьей редакции (от декабря 1999 года).

- -

Новое в JavaScript 1.5

- - - -

Что изменилось в JavaScript 1.5

- - diff --git a/files/ru/web/javascript/new_in_javascript/1.6/index.html b/files/ru/web/javascript/new_in_javascript/1.6/index.html deleted file mode 100644 index 252db0756e..0000000000 --- a/files/ru/web/javascript/new_in_javascript/1.6/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Новое в JavaScript 1.6 -slug: Web/JavaScript/New_in_JavaScript/1.6 -tags: - - JavaScript -translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.6 ---- -
{{jsSidebar("New_in_JS")}}
- -

The following is a changelog for JavaScript 1.6. This version was included in Firefox 1.5 (Gecko 1.8), which was released in November 2005. The corresponding ECMA standard is ECMA-262 Edition 3 and ECMAScript for XML (E4X) with some additional features. Several new features were introduced: E4X, several new Array methods, and Array and String generics.

- -

New features in JavaScript 1.6

- - - -

Changed functionality in JavaScript 1.6

- - diff --git a/files/ru/web/javascript/new_in_javascript/1.8.1/index.html b/files/ru/web/javascript/new_in_javascript/1.8.1/index.html deleted file mode 100644 index eeceb235b3..0000000000 --- a/files/ru/web/javascript/new_in_javascript/1.8.1/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Новое в JavaScript 1.8.1 -slug: Web/JavaScript/New_in_JavaScript/1.8.1 -tags: - - Firefox 3.5 - - JavaScript - - Версии -translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8.1 ---- -
{{jsSidebar("New_in_JS")}}
- -

Ниже приведен список изменений в JavaScript 1.8.1. Эта версия включена в Firefox 3.5.

- -

JavaScript 1.8.1 это скромное обновление синтаксиса на JavaScript; главным изменением является добавление Tracemonkey just-in-time compiler, которое повышает производительность.

- -

Новшества в JavaScript 1.8.1

- - - -

Измененные функции в JavaScript 1.8.1

- - diff --git a/files/ru/web/javascript/new_in_javascript/1.8.5/index.html b/files/ru/web/javascript/new_in_javascript/1.8.5/index.html deleted file mode 100644 index ab6a9d4ce3..0000000000 --- a/files/ru/web/javascript/new_in_javascript/1.8.5/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Новое в JavaScript 1.8.5 -slug: Web/JavaScript/New_in_JavaScript/1.8.5 -translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8.5 ---- -
{{jsSidebar("New_in_JS")}}
- -

Далее приведён список изменений в JavaScript 1.8.5. Эта версия была включена в Firefox 4.

- -

Что нового в JavaScript 1.8.5

- -

Новые функции

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ФункцияОписание
Object.create()Создаёт новый обЪект с указанным прототипом и свойствами. {{bug("492840")}}
Object.defineProperty()Добавляет свойство с переданным дескриптором к объекту.
Object.defineProperties()Добавляет свойства с переданными дескрипторами к объекту.
Object.getOwnPropertyDescriptor()Возвращает дескриптор свойства переданного объекта. {{bug("505587")}}
Object.keys()Возвращает массив всех перечисляемых свойств объекта. {{bug("307791")}}
Object.getOwnPropertyNames()Возвращает массив всех перечисляемых и не перечисляемых свойств объекта. {{bug("518663")}}
Object.preventExtensions()Предотвращает любые расширения объекта. {{bug("492849")}}
Object.isExtensible()Определяет, разрешено ли расширение объекта. {{bug("492849")}}
Object.seal()Запрещает остальному коду удаление свойств объекта {{bug("492845")}}
Object.isSealed()Определяет, запрещено ли удаление свойств объекта. {{bug("492845")}}
Object.freeze()Замораживает объект: остальной код не может удалять или изменять значения его свойств. {{bug("492844")}}
Object.isFrozen()Определяет, был ли объект заморожен. {{bug("492844")}}
Array.isArray()Проверяет, является ли переменная массивом. {{bug("510537")}}
Date.prototype.toJSON()Возвращает строку в формате JSON для объекта Date.
Function.prototype.bind()Метод bind() создаёт новую функцию, которая при вызове устанавливает в качестве контекста выполнения this предоставленное значение. В метод также передаётся набор аргументов, которые будут установлены перед переданными в привязанную функцию аргументами при её вызове.{{bug("429507")}}
- -

Новые возможности ECMAScript5

- - - -

Другая работа по стандартизации

- -

Различные нестандартизованные синтаксические конструкции задания геттеров/сеттеров были удалены; Определенный в  ECMAScript 5 синтаксис изменениям не подвергся. Все они были несколько "эзотерическими" и довольно редко использовались на практике; если эти изменения Вас затронули, прочтите эту статью.

- -

Новые объекты

- - - - - - - - - - - - - - -
ОбъектОписание
ProxyПредлагает поддержку при создании Object и Function прокси, что позволяет использовать метапрограммирование на JavaScript.
- -

Функциональность, изменённая в JavaScript 1.8.5

- - diff --git a/files/ru/web/javascript/new_in_javascript/1.8/index.html b/files/ru/web/javascript/new_in_javascript/1.8/index.html deleted file mode 100644 index 8187682071..0000000000 --- a/files/ru/web/javascript/new_in_javascript/1.8/index.html +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: New in JavaScript 1.8 -slug: Web/JavaScript/New_in_JavaScript/1.8 -tags: - - Версии -translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8 ---- -
{{jsSidebar("New_in_JS")}}
- -

Следующее описание относится к  JavaScript 1.8. Эта версия была включена в Firefox 3 является частью Gecko 1.9. {{ Bug("380236") }} – здесь вы можете просмотреть исправленные в процессе разработки JavaScript 1.8 баги.

- -

Использование JavaScript 1.8

- -

Чтобы воспользоваться преимуществами JavaScript 1.8, используйте следующий синтаксис подключения:

- -
 <script type="application/javascript;version=1.8"> ... your code ... </script>
-
- -

Альтернативным методом является использование устаревшего аттрибута language тэга script. Для этого необходимо установить ему значение JavaScript1.8. Этот способ не рекомендуется к применению.

- -

При использовании JavaScript шеллов, JavaScript XPCOM компонент, или XUL <script> элементов, последняя версия JavaScript (JS1.8 в Mozilla 1.9) будет использована автоматически ({{ Bug(381031) }}, {{ Bug(385159) }}).

- -

Нововведения, которые используют ключевые слова yield и let требуют использования Javascript версии 1.7 или выше, потому как существующий код может использовать эти ключевые слова как названия переменных или функций. Остальные нововведения (например, генераторы) могут быть использованы без указания версии JavaScript.

- -

Новое в JavaScript 1.8

- - - -

Изменения в JavaScript 1.8

- -

Изменения в деструктивном присваивании

- -

Багфикс, который был добавлен в  JavaScript 1.8, решает проблему связанную с деструктивным присваиванием, которое было введено в JavaScript 1.7.  Изменен механизм  деструктуризации массивов при использовании for (var [a,b] in array). Ранее был доступен вызов в форме, описанной выше, однако это вызывало некорректное поведение цикла при работе с итераторами. Проблема решена ({{ Bug("366941") }}). Теперь следует использовать следующий синтаксис: for ( var [key, value] in Iterator(array)).

diff --git a/files/ru/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html b/files/ru/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html deleted file mode 100644 index 50fbcca8b5..0000000000 --- a/files/ru/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Поддержка ECMAScript 5 в Mozilla -slug: Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla -tags: - - ECMAScript5 - - JavaScript - - Versions -translation_of: Archive/Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla ---- -

{{jsSidebar("New_in_JS")}}

- -

Стандарт ECMAScript 5.1, последнее издание стандарта, на котором основан язык JavaScript, был принят в июне 2011 года.

- -

Среда выполнения JavaScript, используемая в последних версиях проектов Mozilla, включающих Firefox и Thunderbird, имеет полную поддержку возможностей ECMAScript 5.1. Эта статья описывает возможности, поддерживаемые разными версиями среды выполнения JavaScript Mozilla.

- -

Поддерживаемые возможности

- -

Добавленные в JavaScript 1.8.5 (Gecko 2, Firefox 4 и более поздние)

- -

Firefox 4 имеет полную поддержку стандарта ECMAScript 5, включая методы Object.* и строгий режим. Смотрите статью Что нового в JavaScript 1.8.5.

- -

Добавленные в JavaScript 1.8.1 (Gecko 1.9.1, Firefox 3.5)

- - - -

Реализованы улучшения в алгоритме разбора, внесённые ECMAScript 5. Изменения предотвращают рассмотрение XHTML в качестве кода на JavaScript, ранее происходившее в определённых обстоятельствах.

- -

Добавленные в JavaScript 1.6 (Gecko 1.8, Firefox 1.5)

- -

Новые методы {{jsxref("Global_Objects/Array", "Array")}}, предлагающие некоторые улучшенные возможности по манипулированию массивами, были частью JavaScript начиная с JavaScript 1.6. Теперь они утверждены как часть стандарта ECMAScript 5.

- -

Смотрите также

- - diff --git a/files/ru/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html b/files/ru/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html deleted file mode 100644 index cfc66e9806..0000000000 --- a/files/ru/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html +++ /dev/null @@ -1,222 +0,0 @@ ---- -title: Поддержка ECMAScript 6 в Mozilla -slug: Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla -tags: - - ECMAScript6 - - JavaScript -translation_of: Archive/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla ---- -

{{jsSidebar("New_in_JS")}}

- -

ECMAScript 2015 - это новая версия стандарта, имеющая кодовое имя "Harmony","ES.next" или "ECMAScript 6". Черновая спецификация может быть найдена в официальном вики ECMA. Первый рабочий черновик, основанный на ECMAScript 5.1, был опубликован 12 июля 2011 как "ES.next". По состоянию на август 2014 в ECMAScript 2015 больше не принимаются новые функции и ожидается окончание работы над ним в конце 2014 с официальной публикацией в марте 2015.

- -

Для получения обратной связи по стандартам ECMAScript используется канал es-discuss.

- -

Поддерживаемые функции

- -

Следующие функции уже реализованы в Firefox:

- -

Стандартная библиотека

- -

Дополнения в объекте Array

- - - -

Новые объекты Map и Set и их слабые аналоги

- - - -

Новые функции в объекте Math

- - - -

Дополнения в объекте Number

- - - -

Дополнения в объекте Object

- - - -

Новый объект Promise

- - - -

Дополнения в объекте RegExp

- - - -

Дополнения в объекте String

- - - -

Новый объект Symbol

- - - -

Типизированные массивы

- -

Типизированные массивы стали часть спецификации ECMAScript 2015, а не только своей собственной.

- - - -

Выражения  и операторы

- - - -

Операторы

- - - -

Функции

- - - -

Другие возможности

- - - -

Стабилизируемые и обсуждаемые функции

- -

Следующие функции частично реализованы в Firefox, но были добавлены до принятия стандарта ES2015 или ещё обсуждаются в стандарте ECMA TC39.

- - - -

Не реализованные функции

- -

Следующие функции включены в черновик спецификации ECMAScript 2015, но пока не реализованы в Firefox:

- - - -

Смотрите также

- - diff --git a/files/ru/web/javascript/new_in_javascript/index.html b/files/ru/web/javascript/new_in_javascript/index.html deleted file mode 100644 index f01f13834f..0000000000 --- a/files/ru/web/javascript/new_in_javascript/index.html +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Что нового в JavaScript -slug: Web/JavaScript/New_in_JavaScript -tags: - - JavaScript - - Versions -translation_of: Archive/Web/JavaScript/New_in_JavaScript ---- -

{{jsSidebar("New_in_JS")}}

- -

Эта глава содержит информацию об истории версий JavaScript и статусе их реализаций в основанных на Mozilla/SpiderMonkey JavaScript-приложениях, таких, как Firefox.

- -

Версии ECMAScript

- -
-
Ресурсы по языку
-
Узнайте больше о стандартах ECMAScript, на которых основывается язык JavaScript.
-
Поддержка ECMAScript 5
-
Статус реализации стандарта ECMA-262 5-го издания в Firefox.
-
Поддержка ECMAScript 6
-
Статус реализации стандарта ECMA-262 6-го издания в Firefox.
-
Поддержка ECMAScript 7
-
Статус реализации стандарта ECMA-262 7-го издания в Firefox.
-
- -

Замечания к выпускам JavaScript

- -
-
Список изменений в JavaScript браузера Firefox
-
Смотрите этот список изменений, чтобы узнать, какие возможности JavaScript реализованы в Firefox 5 и выше.
-
Список изменений в JavaScript браузера Chrome
-
(TODO). Смотрите этот список изменений, чтобы узнать, какие возможности JavaScript реализованы в выпусках Chrome.
-
- -

Версии JavaScript

- -

Устарело ({{deprecated_inline}}). Явное версионирование и выбор возможностей языка было особенностью Mozilla и она находится в процессе удаления. Firefox 4 был последней версией, ссылающийся на версию JavaScript (1.8.5). С новыми стандартами ECMA возможности языка JavaScript часто упоминаются вместе с их первоначальным определением в изданиях ECMA-262, например, с 6-м изданием (ES6).

- -

JavaScript версии 1.0 был выпущен в марте 1996 года в браузерах Netscape Navigator 2.0 и Internet Explorer 2.0.

- -
-
JavaScript 1.1
-
Версия, содержащаяся в браузере Netscape Navigator 3.0. Выпущен 19 августа 1996 года.
-
JavaScript 1.2
-
Версия, содержащаяся в браузерах Netscape Navigator 4.0-4.05. Выпущен 11 июня 1997 года.
-
JavaScript 1.3
-
Версия, содержащаяся в браузерах Netscape Navigator 4.06-4.7x. Выпущен 19 октября 1998 года.
- Работа по стандартизации и совместимости с 1-м и 2-м изданиями ECMA-262.
-
JavaScript 1.4
-
Версия, содержащаяся в серверном JavaScript Netscape. Выпущен в 1999 году.
-
JavaScript 1.5
-
Версия, содержащаяся в браузерах Netscape Navigator 6.0 и Firefox 1.0. Выпущен 14 ноября 2000 года.
- Работа по стандартизации и совместимости с 3-им изданием ECMA-262.
-
JavaScript 1.6
-
Версия, содержащаяся в браузере Firefox 1.5. Выпущен в ноябре 2005 года.
- Включает ECMAScript для XML (E4X), новые методы объекта Array, плюс обобщённые методы объектов String и Array.
-
JavaScript 1.7
-
Версия, содержащаяся в браузере Firefox 2. Выпущен в октябре 2006 года.
- Включает генераторы, итераторы, выражения заполнения массива, выражения let и реструктуризующее присваивание.
-
JavaScript 1.8
-
Версия, содержащаяся в браузере Firefox 3. Выпущен в июне 2008 года.
- Включает выражения замыкания, выражения-генераторы и метод Array.reduce().
-
JavaScript 1.8.1
-
Версия, содержащаяся в браузере Firefox 3.5. Выпущен 30 июня 2009 года.
- Включает компилятор TraceMonkey JIT и поддержку родного JSON.
-
JavaScript 1.8.2
-
Версия, содержащаяся в браузере Firefox 3.6. Выпущен 22 июня 2009 года.
- Включает только незначительные изменения.
-
JavaScript 1.8.5
-
Версия, содержащаяся в браузере Firefox 4. Выпущен 27 июля 2010 года.
- Включает множество новых возможностей, соответствующих 5-му изданию ECMA-262.
- Это последняя версия JavaScript.
-
- -

Возможности, всё ещё требующие определённой версии

- -
-
инструкция let
-
Инструкция let требует версии JavaScript 1.7.
-
diff --git a/files/ru/web/javascript/reference/functions/arguments/caller/index.html b/files/ru/web/javascript/reference/functions/arguments/caller/index.html deleted file mode 100644 index 0b6fe5cc4b..0000000000 --- a/files/ru/web/javascript/reference/functions/arguments/caller/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: arguments.caller -slug: Web/JavaScript/Reference/Functions/arguments/caller -tags: - - Functions - - JavaScript - - Obsolete - - Property - - arguments -translation_of: Archive/Web/JavaScript/arguments.caller ---- -
{{jsSidebar("Functions")}}
- -

Устаревшее свойство arguments.caller использовалось для того, чтобы определить источник вызова функции, выполняющейся в текущий момент времени. Данное свойство было удалено и больше не работает.

- -

Описание

- -

Данное свойство больше не доступно, но вы все так же можете использовать {{jsxref("Function.caller")}}.

- -
function whoCalled() {
-   if (whoCalled.caller == null)
-      console.log('Меня вызвали из глобальной области видимости.');
-   else
-      console.log(whoCalled.caller + ' вызвал меня!');
-}
- -

Примеры

- -

Код, приведенный ниже, больше не работает, но раньше он использовался для проверки значения arguments.caller функции.

- -
function whoCalled() {
-   if (arguments.caller == null)
-      console.log('Меня вызвали из глобальной области видимости.');
-   else
-      console.log(arguments.caller + ' вызвал меня!');
-}
-
- -

Спецификации

- -

Не является частью какого-либо стандарта. Реализовано в JavaScript 1.1 и удалено в {{bug(7224)}}, поскольку влекло за собой потенциальную уязвимость.

- -

Совместимость с браузерами

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}
- удалено в IE 9
{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/global_objects/array/observe/index.html b/files/ru/web/javascript/reference/global_objects/array/observe/index.html deleted file mode 100644 index f8d7d9cd07..0000000000 --- a/files/ru/web/javascript/reference/global_objects/array/observe/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: Array.observe() -slug: Web/JavaScript/Reference/Global_Objects/Array/observe -tags: - - Array - - ECMAScript7 - - Experimental - - Expérimental(2) - - JavaScript - - Method - - Reference - - Référence(2) -translation_of: Archive/Web/JavaScript/Array.observe ---- -
{{JSRef("Global_Objects", "Array")}}
- -

Сводка

- -

Метод Array.observe() используется для асинхронного обзора изменений в массивах, подобно тому, как метод {{jsxref("Object.observe()")}} используется для тех же целей для объектов. Он предоставляет поток изменений в порядке их возникновения.

- -

Синтаксис

- -
Array.observe(arr, callback)
- -

Параметры

- -
-
arr
-
Обозреваемый массив.
-
callback
-
Функция, вызываемая на каждое сделанное изменение со следующими аргументами: -
-
changes
-
Массив объектов, каждый из которых представляет одно изменение. Эти объекты обладают следующими свойствами: -
    -
  • name: название изменённого свойства.
  • -
  • object: изменённый массив, после применения этого изменения.
  • -
  • type: строка, указывающая тип произошедшего изменения. Может быть одной из "add", "update", "delete" или "splice".
  • -
  • oldValue: только для типов "update" и "delete". Значение до изменения.
  • -
  • index: только для типа "splice". Индекс, по которому произошло изменение.
  • -
  • removed: только для типа "splice". Массив с удалёнными элементами.
  • -
  • addedCount: только для типа "splice". Количество добавленных элементов.
  • -
-
-
-
-
- -

Описание

- -

Функция callback вызывается каждый раз, когда с массивом arr происходят какие-либо изменения. Параметром в неё передаётся массив со всеми произошедшими изменениями в порядке их возникновения.

- -
-

Изменения через методы объекта {{jsxref("Array")}}, например, посредством метода {{jsxref("Array.prototype.pop()")}}, будут зарегистрированы как изменения типа "splice". Присваивание по индексу, в результате которого размер массива не изменится, может быть зарегистрировано, как изменение типа "update".

-
- -

Примеры

- -

Пример: журналирование всех трёх типов событий

- -
var arr = ['a', 'b', 'c'];
-
-Array.observe(arr, function(changes) {
-  console.log(changes);
-});
-
-arr[1] = 'B';
-// [{type: 'update', object: <arr>, name: '1', oldValue: 'b'}]
-
-arr[3] = 'd';
-// [{type: 'splice', object: <arr>, index: 3, removed: [], addedCount: 1}]
-
-arr.splice(1, 2, 'beta', 'gamma', 'delta');
-// [{type: 'splice', object: <arr>, index: 1, removed: ['B', 'c', 'd'], addedCount: 3}]
-
- -

Спецификации

- -

Черновое предложение к обсуждению для ECMAScript 7.

- -

Совместимость с браузерами

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/global_objects/date/tolocaleformat/index.html b/files/ru/web/javascript/reference/global_objects/date/tolocaleformat/index.html deleted file mode 100644 index af33b9da2f..0000000000 --- a/files/ru/web/javascript/reference/global_objects/date/tolocaleformat/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Date.prototype.toLocaleFormat() -slug: Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat -tags: - - Date - - JavaScript - - Method - - Non-standard - - Prototype - - Reference -translation_of: Archive/Web/JavaScript/Date.toLocaleFormat ---- -
{{JSRef}} {{non-standard_header}}
- -

Нестандартный метод toLocaleFormat() преобразует дату в строку, используя указанное форматирование. Объект {{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}} является совместимой со стандартами альтернативой при форматировании дат. Так же смотрите новую версию метода {{jsxref("Date.prototype.toLocaleDateString()")}}.

- -

Синтаксис

- -
dateObj.toLocaleFormat(formatString)
- -

Параметры

- -
-
formatString
-
Строка формата в той же форме, что ожидается функцией C strftime().
-
- -

Описание

- -

Метод toLocaleFormat() обеспечивает больший контроль программного обеспечения над форматированием генерируемых даты и/или времени. Названия месяцев и дней недели локализуются с помощью локали операционной системы. Однако, порядок дней и месяцев и другие задачи локализации автоматически не обрабатываются, так как эти аспекты контролируете вы. Вы должны позаботиться о том, что строка формата была правильно локализована в соответствии с настройками системы пользователя. Знайте, что используемая локаль не обязательно совпадает с локалью браузера.

- -

Разработчики расширений и XULRunner должны знать, что загрузку строки формата их файлов .dtd или .properties через URI chrome://somedomain/locale/somefile.ext нужно избегать, поскольку файлы .dtd/.properties и метод toLocaleFormat() не обязательно используют одну и ту же локаль, из-за чего результат может выглядеть странно, неоднозначно или даже нечитаемо.

- -

Также обратите внимание, что поведение локали зависит от платформы и пользователь может настроить эту локаль, так что использование системной локали для выбора строки формата в некоторых случаях может быть даже неадекватным. Вы можете рассмотреть возможность использования более общих методов toLocale* объекта {{jsxref("Global_Objects/Date", "Date")}}, либо написать свою собственную локализацию даты, используя для её отображения методы get* объекта {{jsxref("Global_Objects/Date", "Date")}}.

- -

Примеры

- -

Пример: использование метода toLocaleFormat()

- -
var today = new Date();
-var date = today.toLocaleFormat('%A, %B %e, %Y'); // плохой пример
-
- -

В примере выше метод toLocaleFormat() возвращает строку вида "Wednesday, October 3, 2007". обратите внимание, что строка формата в данном примере не локализуется должным образом, что приводит к проблемам, описанным выше.

- -

Библиотеки

- -

Вы можете использовать библиотеку DateJS, если {{jsxref("Date.prototype.toLocaleDateString","Date.prototype.toLocaleDateString()")}} недоступен:

- -
if (!Date.prototype.toLocaleFormat) {
-    (function() {
-        Date.prototype.toLocaleFormat = function(formatString) {
-            return this.format(formatString);
-        };
-    }());
-}
- -

Спецификации

- -

Не является частью какой-либо спецификации. Реализована в JavaScript 1.6.

- -

Совместимость с браузерами

- -
{{Compat("javascript.builtins.Date.toLocaleFormat")}}
- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/global_objects/function/arity/index.html b/files/ru/web/javascript/reference/global_objects/function/arity/index.html deleted file mode 100644 index 8bcd00363b..0000000000 --- a/files/ru/web/javascript/reference/global_objects/function/arity/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Function.arity -slug: Web/JavaScript/Reference/Global_Objects/Function/arity -tags: - - Function - - JavaScript - - Obsolete - - Property - - Unimplemented -translation_of: Archive/Web/JavaScript/Function.arity ---- -
{{JSRef}}{{Obsolete_Header}}
- -

Свойство arity использовалось для возврата количества ожидаемых функцией аргументов, однако, оно больше не существует и было заменено свойством {{JSxRef("Function.prototype.length")}}.

- -

Спецификации

- -

Реализовано в JavaScript 1.2. Устарело в JavaScript 1.4.

- -

Совместимость с браузерами

- - - -

{{Compat("javascript.builtins.Function.arity")}}

- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/global_objects/function/isgenerator/index.html b/files/ru/web/javascript/reference/global_objects/function/isgenerator/index.html deleted file mode 100644 index e3a972e9e2..0000000000 --- a/files/ru/web/javascript/reference/global_objects/function/isgenerator/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Function.prototype.isGenerator() -slug: Web/JavaScript/Reference/Global_Objects/Function/isGenerator -tags: - - Function - - JavaScript - - Method - - Non-standard -translation_of: Archive/Web/JavaScript/Function.isGenerator ---- -
- {{JSRef("Global_Objects", "Function")}} {{non-standard_header}}
-

Сводка

-

Метод isGenerator() определяет, является ли функция генератором.

-

Синтаксис

-
fun.isGenerator()
-

Описание

-

Метод isGenerator() определяет, является ли функция fun генератором. Он является частью раннего предложения Harmony, но не был включён в спецификацию ECMAScript 6.

-

Примеры

-
function f() {}
-
-function g() {
-  yield 42;
-}
-
-console.log('f.isGenerator() = ' + f.isGenerator()); // f.isGenerator() = false
-console.log('g.isGenerator() = ' + g.isGenerator()); // g.isGenerator() = true
-
-

Спецификации

-

Не является частью какой-либо спецификации. Реализована в JavaScript 1.8.6.

-

Совместимость с браузерами

-
- {{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatGeckoDesktop("5.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("5.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-

Смотрите также

- diff --git a/files/ru/web/javascript/reference/global_objects/iterator/index.html b/files/ru/web/javascript/reference/global_objects/iterator/index.html deleted file mode 100644 index 0a55a44af9..0000000000 --- a/files/ru/web/javascript/reference/global_objects/iterator/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: Iterator -slug: Web/JavaScript/Reference/Global_Objects/Iterator -tags: - - JavaScript - - Reference -translation_of: Archive/Web/Iterator ---- -
{{jsSidebar("Objects")}}
- -
 
- -
-

Non-standard. The Iterator function is a SpiderMonkey-specific feature, and will be removed at some point. For future-facing usages, consider using for..of loops and the iterator protocol.

-
- -

The Iterator function returns an object which implements legacy iterator protocol and iterates over enumerable properties of an object.

- -

Syntax

- -
Iterator(object, [keyOnly])
- -

Parameters

- -
-
object
-
Object to iterate over properties.
-
keyOnly
-
If keyOnly is truthy value, Iterator.prototype.next returns property_name only.
-
- -

Description

- -

Returns Iterator instance that iterates over objectIterator instance returns [property_name, property_value] array for each iteration if keyOnly is falsy,  otherwise, if keyOnly is truthy, it returns property_name for each iteration.  If object is the Iterator instance or Generator instance, it returns object itself.

- -

Properties

- -
-
Iterator.prototype[@@iterator]
-
Returns a function that returns iterator object.
-
- -

Methods

- -
-
Iterator.prototype.next
-
Returns next item in the [property_name, property_value] format or property_name only. It throws StopIteration if there are no more items.
-
- -

Examples

- -

Iterating over properties of an object

- -
var a = {
-  x: 10,
-  y: 20,
-};
-var iter = Iterator(a);
-console.log(iter.next()); // ["x", 10]
-console.log(iter.next()); // ["y", 20]
-console.log(iter.next()); // throws StopIteration
- -

Iterating over properties of an object with legacy destructuring for-in statement

- -
var a = {
-  x: 10,
-  y: 20,
-};
-
-for (var [name, value] in Iterator(a)) {
-  console.log(name, value);   // x 10
-                              // y 20
-}
- -

Iterating with for-of

- -
var a = {
-  x: 10,
-  y: 20,
-};
-
-for (var [name, value] of Iterator(a)) {  // @@iterator is used
-  console.log(name, value);   // x 10
-                              // y 20
-}
- -

Iterates over property name

- -
var a = {
-  x: 10,
-  y: 20,
-};
-
-for (var name in Iterator(a, true)) {
-  console.log(name);   // x
-                       // y
-}
- -

Passing Generator instance

- -
function* f() {
-  yield 'a';
-  yield 'b';
-}
-var g = f();
-
-console.log(g == Iterator(g)); // true
-
-for (var v in Iterator(g)) {
-  console.log(v);   // a
-                    // b
-}
- -

Passing Iterator instance

- -
var a = {
-  x: 10,
-  y: 20,
-};
-
-var i = Iterator(a);
-
-console.log(i == Iterator(i)); // true
- -

Specifications

- -

Non-standard. Not part of any current standards document

- -

Browser compatibility

- -

Not supported. Used to be in Firefox in versions prior to Firefox 57.

- -

See also

- - diff --git a/files/ru/web/javascript/reference/global_objects/number/tointeger/index.html b/files/ru/web/javascript/reference/global_objects/number/tointeger/index.html deleted file mode 100644 index 14260df0d5..0000000000 --- a/files/ru/web/javascript/reference/global_objects/number/tointeger/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Number.toInteger() -slug: Web/JavaScript/Reference/Global_Objects/Number/toInteger -tags: - - JavaScript - - Method - - Non-standard - - Number - - Obsolete -translation_of: Archive/Web/JavaScript/Number.toInteger ---- -
{{JSRef("Global_Objects", "Number")}} {{obsolete_header("33")}} {{non-standard_header}}
- -

Сводка

-

Метод Number.toInteger() использовался для вычисления переданного значения и преобразования его в целое число, но его реализация была удалена.

-

Если целевым значением является {{jsxref("Global_Objects/NaN", "NaN")}}, {{jsxref("Global_Objects/null", "null")}} или {{jsxref("Global_Objects/undefined", "undefined")}}, возвращается 0. Если целевым значением является false, возвращается 0, а если true, то 1.

- -

Синтаксис

-
Number.toInteger(number)
- -

Параметры

-
-
number
-
Значение, преобразуемое в целое число.
-
- -

Примеры

- -

Пример: использование toInteger

-

Вывод на некоторых тестовых значениях:

-
Number.toInteger(0.1);     // 0
-Number.toInteger(1);       // 1
-Number.toInteger(Math.PI); // 3
-Number.toInteger(null);    // 0
-
- -

Спецификации

- - -

Совместимость с браузерами

-
{{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}Firefox с версии 16 по версию 32{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}Firefox с версии 16 по версию 32{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Смотрите также

- diff --git a/files/ru/web/javascript/reference/global_objects/object/count/index.html b/files/ru/web/javascript/reference/global_objects/object/count/index.html deleted file mode 100644 index 7308b40b0f..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/count/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Object.prototype.__count__ -slug: Web/JavaScript/Reference/Global_Objects/Object/count -tags: - - JavaScript - - Object - - Obsolete - - Property - - Prototype - - Reference -translation_of: Archive/Web/JavaScript/Object.count ---- -
{{JSRef("Global_Objects", "Object")}} {{obsolete_header("2")}}
- -

Сводка

-

Свойство __count__ использовалось для хранения количества перечисляемых свойств объекта, но было удалено.

- -

Синтаксис

-
obj.__count__
- -

Пример

-
{ 1: 1 }.__count__              // 1
-[].__count__                    // 0
-[1].__count__                   // 1
-[1, /* дыра */, 2, 3].__count__ // 3
-
- -

Спецификации

-

Не является частью какой-либо спецификации.

- -

Совместимость с браузерами

-
{{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Смотрите также

- diff --git a/files/ru/web/javascript/reference/global_objects/object/eval/index.html b/files/ru/web/javascript/reference/global_objects/object/eval/index.html deleted file mode 100644 index e6b8e3668f..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/eval/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Object.prototype.eval() -slug: Web/JavaScript/Reference/Global_Objects/Object/eval -tags: - - JavaScript - - Method - - Object - - Obsolete - - Prototype -translation_of: Archive/Web/JavaScript/Object.eval ---- -
- {{JSRef("Global_Objects", "Object")}} {{obsolete_header}}
-

Сводка

-

Метод Object.eval() использовался для вычисления строки JavaScript-кода в контексте объекта, однако, был удалён.

-

Синтаксис

-
obj.eval(string)
-

Параметры

-
-
- string
-
- Любая строка, представляющая выражение, инструкцию или последовательность инструкций JavaScript. Выражение может содержать переменые и свойства существующих объектов.
-
-

Описание

-

Метод eval больше не используется как метод объекта. Вместо него используйте глобальную функцию {{jsxref("Global_Objects/eval", "eval()")}}.

-

Спецификации

-

Не является частью какой-либо спецификации.

-

Совместимость с браузерами

-
- {{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-

Смотрите также

- diff --git a/files/ru/web/javascript/reference/global_objects/object/getnotifier/index.html b/files/ru/web/javascript/reference/global_objects/object/getnotifier/index.html deleted file mode 100644 index 1947d51f73..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/getnotifier/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Object.getNotifier() -slug: Web/JavaScript/Reference/Global_Objects/Object/getNotifier -translation_of: Archive/Web/JavaScript/Object.getNotifier ---- -
{{JSRef}} {{obsolete_header}}
- -

Метод Object.getNotifer() использовался для создания объекта, который позволяет синтетически инициировать изменение, но не рекомендуется  и удаляется в браузерах.

- -

Синтаксис

- -
Object.getNotifier(obj)
- -

Параметры

- -
-
obj
-
Объект для извлечения уведомителя.
-
- -

Возращаемое значение

- -

Объект увидомителя, связанный с объектом, передаваемым в функцию.

- -

Описание

- -

Уведомитель используется для запуска искусственных изменений, которые будут обнаружены Object.observe().

- -

Спецификации

- -

Strawman proposal specification.

- -

Совместимость с браузерами

- -
- - -

{{Compat("javascript.builtins.Object.getNotifier")}}

-
- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/global_objects/object/nosuchmethod/index.html b/files/ru/web/javascript/reference/global_objects/object/nosuchmethod/index.html deleted file mode 100644 index 6f0827751f..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/nosuchmethod/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Object.prototype.__noSuchMethod__ -slug: Web/JavaScript/Reference/Global_Objects/Object/noSuchMethod -tags: - - JavaScript - - Non-standard - - Object - - Property - - Prototype - - Reference -translation_of: Archive/Web/JavaScript/Object.noSuchMethod ---- -
{{JSRef("Global_Objects", "Object")}} {{non-standard_header}}
- -
Хотя свойство __noSuchMethod__ и нестандартно, спецификация ECMAScript Harmony (ES6) содержит объект {{jsxref("Proxy")}}, с помощью которого вы можете сделать всё тоже самое, что и при использовании этого свойством (и даже больше).
- -

Сводка

-

Свойство __noSuchMethod__ ссылается на функцию, выполняющуюся каждый раз при вызове на объекте несуществующего метода.

- -

Синтаксис

-
obj.__noSuchMethod__ = fun
- -

Параметры

-
-
fun
-
Функция, имеющая вид
-
-
function(id, args) { . . . }
-
-
id
-
Имя вызванного несуществующего метода
-
args
-
Массив аргументов, переданный в метод
-
-
-
- -

Описание

-

По умолчанию, при попытке вызвать не существующий в объекте метод, будет выброшено исключение {{jsxref("Global_Objects/TypeError", "TypeError")}}. Это поведение можно обойти, определив функцию __noSuchMethod__ в качестве члена объекта. Функция принимает два аргумента, первый является именем метода, который попытались вызвать, а второй — массивом аргументов, которые были переданы в метод при его вызове. Второй аргумент является настойщим массивом (то есть, он наследуется через цепочку прототипов от {{jsxref("Array.prototype")}}), а не массивоподобным объектом arguments.

-

Если данный метод не может быть вызван, либо по причине того, что он установлен в {{jsxref("Global_Objects/undefined", "undefined")}} по умолчанию, либо удалён, либо вручную установлен в не-функцию, движок JavaScript вернётся к выбрасыванию исключения {{jsxref("Global_Objects/TypeError", "TypeError")}}.

- -

Примеры

- -

Пример: простая проверка свойства __noSuchMethod__

-
var o = {
-    __noSuchMethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); }
-};
-
-o.foo(1, 2, 3);
-o.bar(4, 5);
-o.baz();
-
-// Вывод
-// foo (1, 2, 3)
-// bar (4, 5)
-// baz ()
-
- -

Пример: использование свойства __noSuchMethod__ для симуляции множественного наследования

-

Ниже показан пример кода, реализующего примитивную форму множественного наследования.

-
// Не работает с множественным наследованием объектов в качестве родителей
-function noMethod(name, args) {
-    var parents = this.__parents_;
-
-    // Пройдёмся по всем родителям
-    for (var i = 0; i < parents.length; i++) {
-        // Если нашли функцию в родителе, вызовем её
-        if (typeof parents[i][name] == 'function') {
-            return parents[i][name].apply(this, args);
-        }
-    }
-
-    // Если мы здесь, метод не был найден
-    throw new TypeError;
-}
-
-// Используется для добавления родителя при множественном наследовании
-function addParent(obj, parent) {
-    // Если объект ещё не инициализирован, инициализируем его
-    if (!obj.__parents_) {
-        obj.__parents_ = [];
-        obj.__noSuchMethod__ = noMethod;
-    }
-
-    // Добавляем родителя
-    obj.__parents_.push(parent);
-}
-
-

Ниже показан пример использования этой идеи.

-
// Пример первого базового класса
-
-function NamedThing(name) {
-    this.name = name;
-}
-
-NamedThing.prototype = {
-    getName: function() { return this.name; },
-    setName: function(newName) { this.name = newName; }
-}
-
-// Пример второго базового класса
-
-function AgedThing(age){
-    this.age = age;
-}
-
-AgedThing.prototype = {
-    getAge: function() { return this.age; },
-    setAge: function(age) { this.age = age; }
-}
-
-// Дочерний класс. Наследуется от NamedThing и AgedThing, а также определяет свойство address
-
-function Person(name, age, address) {
-    addParent(this, NamedThing.prototype);
-    NamedThing.call(this, name);
-    addParent(this, AgedThing.prototype);
-    AgedThing.call(this, age);
-    this.address = address;
-}
-
-Person.prototype = {
-    getAddr: function() { return this.address; },
-    setAddr: function(addr) { this.address = addr; }
-}
-
-var bob = new Person('Боб', 25, 'Нью-Йорк');
-
-console.log('getAge лежит ' + (('getAge' in bob) ? 'в' : 'не в') + ' объекте bob');
-console.log('возраст Боба: ' + bob.getAge());
-console.log('getName лежит ' + (('getName' in bob) ? 'в' : 'не в') + ' объекте bob');
-console.log('имя Боба: ' + bob.getName());
-console.log('getAddr лежит ' + (('getAddr' in bob) ? 'в' : 'не в') + ' объекте bob');
-console.log('адрес Боба: ' + bob.getAddr());
-
-

Вывод примера будет следующим:

-
getAge лежит не в объекте bob
-возраст Боба: 25
-getName лежит не в объекте bob
-имя Боба: Боб
-getAddr лежит в объекте bob
-адрес Боба: Нью-Йорк
-
- -

Спецификации

-

Не является частью какой-либо спецификации.

- -

Совместимость с браузерами

-
{{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatGeckoDesktop("1.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("1.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
diff --git a/files/ru/web/javascript/reference/global_objects/object/observe/index.html b/files/ru/web/javascript/reference/global_objects/object/observe/index.html deleted file mode 100644 index 25fe9c879b..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/observe/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Object.observe() -slug: Web/JavaScript/Reference/Global_Objects/Object/observe -tags: - - ECMAScript7 - - Experimental - - JavaScript - - Method - - Object - - Reference -translation_of: Archive/Web/JavaScript/Object.observe ---- -
{{JSRef("Global_Objects", "Object")}}
- -

Сводка

- -

Метод Object.observe() используется для асинхронного обзора изменений в объекте. Он предоставляет поток изменений в порядке их возникновения.

- -

Синтаксис

- -
Object.observe(obj, callback)
- -

Параметры

- -
-
obj
-
Обозреваемый объект.
-
callback
-
Функция, вызываемая при возникновении изменений в объекте, принимает следующий аргумент: -
-
changes
-
Массив объектов, представляющих одно изменение. Объекты с изменениями содержат следующие свойства: -
    -
  • name: имя изменённого свойства.
  • -
  • object: изменённый объект после изменения.
  • -
  • type: строка, указывающая тип произошедшего изменения. Может принимать одно из значений: "add", "update" или "delete".
  • -
  • oldValue: только для типов "update" и "delete". Значение до изменения.
  • -
-
-
-
-
- -

Описание

- -

Функция callback вызывается каждый раз при возникновении изменений в объекте obj с массивом всех изменений в порядке их возникновения.

- -

Примеры

- -

Пример: журналирование всех трёх типов изменений

- -
var obj = {
-  foo: 0,
-  bar: 1
-};
-
-Object.observe(obj, function(changes) {
-  console.log(changes);
-});
-
-obj.baz = 2;
-// [{name: 'baz', object: <obj>, type: 'add'}]
-
-obj.foo = 'hello';
-// [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}]
-
-delete obj.baz;
-// [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}]
-
- -

Пример: привязка данных

- -
// Пользовательская модель
-var user = {
-  id: 0,
-  name: 'Брендан Айк',
-  title: 'М-р.'
-};
-
-// Создаёт приветствие для пользователя
-function updateGreeting() {
-  user.greeting = 'Здравствуйте, ' + user.title + ' ' + user.name + '!';
-}
-updateGreeting();
-
-Object.observe(user, function(changes) {
-  changes.forEach(function(change) {
-    // Любое изменение имени или обращения обновит привествие
-    if (change.name === 'name' || change.name === 'title') {
-      updateGreeting();
-    }
-  });
-});
-
- -

 

- -

Custom change type

- -
// A point on a 2D plane
-var point = {x: 0, y: 0, distance: 0};
-
-function setPosition(pt, x, y) {
-  // Performing a custom change
-  Object.getNotifier(pt).performChange('reposition', function() {
-    var oldDistance = pt.distance;
-    pt.x = x;
-    pt.y = y;
-    pt.distance = Math.sqrt(x * x + y * y);
-    return {oldDistance: oldDistance};
-  });
-}
-
-Object.observe(point, function(changes) {
-  console.log('Distance change: ' + (point.distance - changes[0].oldDistance));
-}, ['reposition']);
-
-setPosition(point, 3, 4);
-// Distance change: 5
- -

 

- -

Спецификации

- -

Черновое предложение к обсуждению для ECMAScript 7.

- -

Совместимость с браузерами

- -
 
- - - -

{{Compat("javascript.builtins.Object.observe")}}

- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/global_objects/object/parent/index.html b/files/ru/web/javascript/reference/global_objects/object/parent/index.html deleted file mode 100644 index d9e5c1ddd9..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/parent/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Object.prototype.__parent__ -slug: Web/JavaScript/Reference/Global_Objects/Object/parent -tags: - - JavaScript - - Object - - Obsolete - - Property - - Prototype -translation_of: Archive/Web/JavaScript/Object.parent ---- -
- {{JSRef("Global_Objects", "Object")}} {{obsolete_header("2")}}
-

Сводка

-

Свойство __parent__ использовалось для указания контекста объекта, но было удалено.

-

Синтаксис

-
obj.__parent__
-

Описание

-

Для объектов верхнего уровня, это, например, окно.

-

Спецификации

-

Не является частью какой-либо спецификации.

-

Совместимость с браузерами

-
- {{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-

Смотрите также

- diff --git a/files/ru/web/javascript/reference/global_objects/object/unobserve/index.html b/files/ru/web/javascript/reference/global_objects/object/unobserve/index.html deleted file mode 100644 index bf3ef676f3..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/unobserve/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Object.unobserve() -slug: Web/JavaScript/Reference/Global_Objects/Object/unobserve -translation_of: Archive/Web/JavaScript/Object.unobserve ---- -
{{JSRef}} {{obsolete_header}}
- -

Метод Object.unobserve() удаляет наблюдатель, который был добавлен с помощью {{jsxref("Object.observe()")}}. Вы можете использовать {{jsxref("Proxy")}} вместо данного метода.

- -

Синтаксис

- -
Object.unobserve(obj, callback)
- -

Параметры

- -
-
obj
-
Объект, за которым необходимо прекратить наблюдение.
-
callback
-
Ссылка на наблюдатель, который нужно остановить на obj.
-
- -

Возаращаемое значение

- -

Указанный объект.

- -

Описание

- -

Object.unobserve() вызывается после {{jsxref("Object.observe()")}}, чтобы удалить наблюдатель на объекте.

- -

В callback нужно передавать ссылку на функцию, которая не является анонимной. Если вызвать Object.unobserve() с анонмной функцией в callback, то ни один наблюдатель не будет удалён.

- -

Примеры

- -

Удаление наблюдателя с объекта

- -
var obj = {
-  foo: 0,
-  bar: 1
-};
-
-var observer = function(changes) {
-  console.log(changes);
-}
-
-Object.observe(obj, observer);
-​
-obj.newProperty = 2;
-// [{name: 'newProperty', object: <obj>, type: 'add'}]
-
-Object.unobserve(obj, observer);
-
-obj.foo = 1;
-// callback не был вызван
- -

Вызов с анонимной функцией

- -
var person = {
-  name: 'Ahmed',
-  age: 25
-};
-
-Object.observe(person, function(changes) {
-  console.log(changes);
-});
-
-person.age = 40;
-// [{name: 'age', object: <obj>, oldValue: 25, type: 'update'}]
-
-Object.unobserve(person, function(changes) {
-  console.log(changes);
-});
-
-person.age = 63;
-// [{name: 'age', object: <obj>, oldValue: 40, type: 'update'}]
-// callback был вызван
-
- -

Спецификации

- -

Strawman proposal specification.

- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Object.unobserve")}}

-
- -

See also

- - diff --git a/files/ru/web/javascript/reference/global_objects/object/unwatch/index.html b/files/ru/web/javascript/reference/global_objects/object/unwatch/index.html deleted file mode 100644 index e862406f3d..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/unwatch/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Object.prototype.unwatch() -slug: Web/JavaScript/Reference/Global_Objects/Object/unwatch -tags: - - JavaScript - - Method - - Non-standard - - Object - - Prototype -translation_of: Archive/Web/JavaScript/Object.unwatch ---- -
- {{JSRef("Global_Objects", "Object")}}
-
-

Предупреждение: обычно, при возможности, вам следует избегать использования unwatch() и {{jsxref("Object.prototype.watch", "watch()")}}. Эти два метода реализованы только в Gecko, и они, в основном, предназначены только для отладочных целей. Кроме того, использование точек наблюдения серьёзно бъёт по производительности, что особенно заметно при использовании их на глобальных объектах, например window. Обычно вместо них вы можете использовать сеттеры и геттеры или прокси. Для более подробной информации смотрите раздел {{anch("Browser_compatibility", "Совместимость с браузерами")}}.

-
-

Сводка

-

Метод unwatch() удаляет точку наблюдения, установленную методом {{jsxref("Object.prototype.watch", "watch()")}}.

-

Синтаксис

-
obj.unwatch(prop)
-

Параметры

-
-
- prop
-
- Имя свойства объекта, чьи изменения вы хотите прекратить отслеживать.
-
-

Описание

-

Отладчик JavaScript имеет функциональность, аналогичную предоставляемой этим методом, а также и другие возможности отладки. Информацию по отладчику можно получить в статье про Venkman.

-

По умолчанию, этот метод наследуется каждым объектом, произошедшим от {{jsxref("Global_Objects/Object", "Object")}}.

-
-

Примечание: причина, по которой метод unwatch() принимает единственным параметром только имя свойства prop в том, что для метода {{jsxref("Object.watch", "watch()")}} разрешён только один обработчик.

-
-

Примеры

-

Смотрите метод {{jsxref("Object.watch", "watch()")}}.

-

Спецификации

-

Не является частью какой-либо спецификации. Реализована в JavaScript 1.2.

-

Совместимость с браузерами

-
- {{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
-

Примечание: вызов unwatch() на объекте {{domxref("Document")}}, начиная с Firefox 23, выбрасывает исключение {{jsxref("Global_Objects/TypeError", "TypeError")}} ({{bug(903332)}}). Эта регрессия была поправлена в Firefox 27.

-
-

Смотрите также

- diff --git a/files/ru/web/javascript/reference/global_objects/object/watch/index.html b/files/ru/web/javascript/reference/global_objects/object/watch/index.html deleted file mode 100644 index 8f4a3d5b99..0000000000 --- a/files/ru/web/javascript/reference/global_objects/object/watch/index.html +++ /dev/null @@ -1,168 +0,0 @@ ---- -title: Object.prototype.watch() -slug: Web/JavaScript/Reference/Global_Objects/Object/watch -tags: - - JavaScript - - Method - - Non-standard - - Object - - Prototype -translation_of: Archive/Web/JavaScript/Object.watch ---- -
- {{JSRef("Global_Objects", "Object")}}
-
-

Предупреждение: обычно, при возможности, вам следует избегать использования watch() и {{jsxref("Object.prototype.unwatch", "unwatch()")}}. Эти два метода реализованы только в Gecko, и они, в основном, предназначены только для отладочных целей. Кроме того, использование точек наблюдения серьёзно бъёт по производительности, что особенно заметно при использовании их на глобальных объектах, например window. Обычно вместо них вы можете использовать сеттеры и геттеры или прокси. Для более подробной информации смотрите раздел {{anch("Browser_compatibility", "Совместимость с браузерами")}}. Также, не путайте {{jsxref("Object.prototype.watch", "Object.watch")}} с {{jsxref("Object.prototype.observe", "Object.observe")}}.

-
-

Сводка

-

Метод watch() следит за присваиванием свойству значений и запускает указанную функцию, когда это происходит.

-

Синтаксис

-
obj.watch(prop, handler)
-

Параметры

-
-
- prop
-
- Имя свойства объекта, чьи изменения вы хотите отслеживать.
-
- handler
-
- Функция, вызывающаяся при изменении значения указанного свойства.
-
-

Описание

-

Следит за присваиваниями свойству prop в этом объекте, вызывая функцию handler(prop, oldval, newval) всякий раз, когда свойство prop устанавливается и сохраняет возвращённое значение в этом свойстве. Точка наблюдения может отфильтровывать (или отменять) присваивание значения, возвращая изменённое новое значение newval (или старое значение oldval).

-

Если вы удалите свойство, для которого была установлена точка наблюдения, эта точка наблюдения не будет отключена. Если вы позже вновь создадите это свойство, точка наблюдения продолжит работать.

-

Для удаления точки наблюдения используйте метод {{jsxref("Object.unwatch", "unwatch()")}}. По умолчанию, метод watch наследуется каждым объектом, произошедшим от {{jsxref("Global_Objects/Object", "Object")}}.

-

Отладчик JavaScript имеет функциональность, аналогичную предоставляемой этим методом, а также и другие возможности отладки. Информацию по отладчику можно получить в статье про Venkman.

-

В Firefox, функция handler вызывает только при присваивании из скрипта, не из встроенного кода. Например, window.watch('location', myHandler) не вызовет myHandler, если пользователь щёлкнет по ссылке с якорем в текущем документе. Однако, выражение window.location += '#myAnchor' вызовет myHandler.

-
-

Примечание: вызов watch() на объекте для определённого свойства перезапишет любые ранее назначенные на него обработчики.

-
-

Примеры

-

Пример: использование watch и unwatch

-
var o = { p: 1 };
-
-o.watch('p', function (id, oldval, newval) {
-  console.log('o.' + id + ' изменено с ' + oldval + ' на ' + newval);
-  return newval;
-});
-
-o.p = 2;
-o.p = 3;
-delete o.p;
-o.p = 4;
-
-o.unwatch('p');
-o.p = 5;
-
-

Этот скрипт выведет следующее:

-
o.p изменено с 1 на 2
-o.p изменено с 2 на 3
-o.p изменено с undefined на 4
-
-

Пример: использование watch для проверки свойств объекта

-

Вы можете использовать watch для проверки присваивания к любым свойствам объекта. Этот пример гарантирует, что каждый человек имеет допустимое имя и возраст между 0 и 200.

-
Person = function(name, age) {
-  this.watch('age', Person.prototype._isValidAssignment);
-  this.watch('name', Person.prototype._isValidAssignment);
-  this.name = name;
-  this.age = age;
-};
-
-Person.prototype.toString = function() {
-  return this.name + ', ' + this.age;
-};
-
-Person.prototype._isValidAssignment = function(id, oldval, newval) {
-  if (id === 'name' && (!newval || newval.length > 30)) {
-    throw new RangeError('недопустимое имя для ' + this);
-  }
-  if (id === 'age'  && (newval < 0 || newval > 200)) {
-    throw new RangeError('недопустимый возраст для ' + this);
-  }
-  return newval;
-}
-
-will = new Person('Уилл', 29);
-print(will);   // Уилл, 29
-
-try {
-  will.name = '';
-} catch (e) {
-  print(e);
-}
-
-try {
-  will.age = -4;
-} catch (e) {
-  print(e);
-}
-
-

Этот скрипт выведет следующее:

-
Уилл, 29
-RangeError: недопустимое имя для Уилл, 29
-RangeError: недопустимый возраст для Уилл, 29
-
-

Спецификации

-

Не является частью какой-либо спецификации. Реализована в JavaScript 1.2.

-

Совместимость с браузерами

- -
- {{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
-
-

Примечание: вызов watch() на объекте {{domxref("Document")}}, начиная с Firefox 23, выбрасывает исключение {{jsxref("Global_Objects/TypeError", "TypeError")}} ({{bug(903332)}}). Эта регрессия была поправлена в Firefox 27.

-
-

Смотрите также

- diff --git a/files/ru/web/javascript/reference/global_objects/parallelarray/index.html b/files/ru/web/javascript/reference/global_objects/parallelarray/index.html deleted file mode 100644 index ca96e4c0fa..0000000000 --- a/files/ru/web/javascript/reference/global_objects/parallelarray/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: ParallelArray -slug: Web/JavaScript/Reference/Global_Objects/ParallelArray -translation_of: Archive/Web/ParallelArray ---- -

{{jsSidebar("Objects")}} {{ obsolete_header() }}

-
-

Note: This object was implemented in Firefox 17 and has been removed from {{ Gecko(29) }} in favor of ParallelJS (PJS) currently available in the Nightly channel ({{ bug(944074) }}).

-
-

Сводка

-

Целью ParallelArray является распараллеливание данных в веб-приложениях. Все функции, которые доступны на простом массиве могут исполняться параллельно на ParallelArray, при необходимости можно вернуться к последовательному исполнению. Чтобы убедиться что ваш код исполняется параллельно, it is suggested that the functions should be limited to the parallelizable subset of JS that Firefox supports.

-

Синтаксис

-
new ParallelArray()
-new ParallelArray([element0, element1, ...])
-new ParallelArray(arrayLength, elementalFunction)
-

Экземпляры ParallelArray

-

Свойства

-
-
- length
-
- Возвращает количество элементов в ParallelArray.
-
-

Методы

-
-
- map
-
- reduce
-
- scan
-
- scatter
-
- filter
-
- flatten
-
- partition
-
- get
-
-

Примеры

-

Пример: Использование метода map параллельно

-
var p = new ParallelArray([0, 1, 2, 3, 4]);
-var m = p.map(function (v) {
-  return v + 1;
-});
-

Смотрите также

- diff --git a/files/ru/web/javascript/reference/global_objects/string/quote/index.html b/files/ru/web/javascript/reference/global_objects/string/quote/index.html deleted file mode 100644 index 367f9f6eb7..0000000000 --- a/files/ru/web/javascript/reference/global_objects/string/quote/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: String.prototype.quote() -slug: Web/JavaScript/Reference/Global_Objects/String/quote -tags: - - JavaScript - - Method - - Obsolete - - Prototype - - Reference - - Référence(2) - - String -translation_of: Archive/Web/JavaScript/String.quote ---- -
{{obsolete_header("37")}}
- -
{{JSRef("Global_Objects", "String")}} {{non-standard_header}}
- -

Сводка

- -

Нестандартный метод quote() возвращает копию строки, заменяя различные специальные символы в строке их управляющими последовательностями и заключая результат в двойные кавычки (").

- -

Синтаксис

- -
str.quote()
- -

Примеры

- -

В таблице ниже метод quote() заменяет любые специальные символы и заключает строку в двойные кавычки. Также обратите внимание на третью колонку, в которой функция {{jsxref("Global_Objects/eval", "eval()")}} снова вычисляет управляющие последовательности.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
strstr.quote()eval(str.quote())
Hello world!"Hello world!"Hello world!
Hello
- world!
"Hello\n\tworld!"Hello
- world!
" \ — '"\" \\ \u2014 '"" \ — '
Привет, мир!"\u041F\u0440\u0438\u0432\u0435\u0442, \u043C\u0438\u0440!"Привет, мир!
- -

Спецификации

- -

Не является частью какого-либо стандарта. Реализована в JavaScript 1.3.

- -

Совместимость с браузерами

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome для AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/operators/array_comprehensions/index.html b/files/ru/web/javascript/reference/operators/array_comprehensions/index.html deleted file mode 100644 index c2bed1585e..0000000000 --- a/files/ru/web/javascript/reference/operators/array_comprehensions/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Упрощенный синтаксис создания массивов -slug: Web/JavaScript/Reference/Operators/Array_comprehensions -translation_of: Archive/Web/JavaScript/Array_comprehensions ---- -
Non-standard. Do not use!
-Сокращенный синтаксис создания массивов не стандартен. В будущем используйте {{jsxref("Array.prototype.map")}}, {{jsxref("Array.prototype.filter")}}, {{jsxref("Functions/Arrow_functions", "Стрелочные функции", "", 1)}} и {{jsxref("Operators/Spread_operator", "spread syntax", "", 1)}}.
- -
{{jsSidebar("Operators")}}
- -

Синтаксис array comprehension - это JavaScript-выражение, которое позволяет быстро создавать новый массив из существующего. Аналогичные сокращения существуют во многих других языках программирования.

- -

Ниже показаны различия со старым синтаксисом Array Comprehension в SpiderMonkey, основанном на черновиках для ECMAScript 4.

- -

Синтаксис

- -
[for (x of итерируемый_объект) x]
-[for (x of итерируемый_объект) if (условие) x]
-[for (x of итерируемый_объект) for (y of итерируемый_объект) x + y]
-
- -

Описание

- -

Внутри сокращения допустимо использование двух видов компонентов:

- - - -

Итерация for-of всегда является первым компонентом. Допустимо использование нескольких for-of итераций или условных операторов if.

- -

Сокращённый синтаксис создания массивов был предложен к стандартизации в ECMAScript 2016, он предоставлял удобный сокращения для создания новых массивов из других массивов. Сокращения могут быть использованы вместо вызовов {{jsxref("Array.prototype.map", "map()")}} и {{jsxref("Array.prototype.filter", "filter()")}} или их комбинаций.

- -

Следующий пример показывает, как из массива чисел создаётся новый массив чисел с с удвоенным значением.

- -
var numbers = [1, 2, 3, 4];
-var doubled = [for (i of numbers) i * 2];
-console.log(doubled); // logs 2,4,6,8
- -

Это эквивалентно следующей операции с {{jsxref("Array.prototype.map", "map()")}}:

- -
var doubled = numbers.map(i => i * 2);
- -

Сокращённый синтаксис может быть использован также для выбора элементов по определённому условию. Вывод четных чисел:

- -
var numbers = [1, 2, 3, 21, 22, 30];
-var evens = [for (i of numbers) if (i % 2 === 0) i];
-console.log(evens); // logs 2,22,30
- -

{{jsxref("Array.prototype.filter", "filter()")}} может использоваться для той же цели:

- -
var evens = numbers.filter(i => i % 2 === 0);
- -

Стили операторов {{jsxref("Array.prototype.map", "map()")}} и {{jsxref("Array.prototype.filter", "filter()")}} можно одновременно использовать в одном сокращённом выражении. Далее фильтруются только четные числа, а затем создаётся массив с их удвоенным значением:

- -
var numbers = [1, 2, 3, 21, 22, 30];
-var doubledEvens = [for (i of numbers) if (i % 2 === 0) i * 2];
-console.log(doubledEvens); // logs 4,44,60
- -

Квадратные скобки обозначают неявный блок. Новый переменные (такие как  "i" в примере выше) трактуются, как если бы они объявлялись с использованием {{jsxref("Statements/let","let")}}. Это значит, что эти переменные недоступны извне.

- -

Входными данными необязательно может быть массив; также можно использовать итераторы и генераторы.

- -

Даже строки могут подаваться на вход; можно делать то же, что с filter и map (но с массивоподобными объектами):

- -
var str = 'abcdef';
-var consonantsOnlyStr = [for (c of str) if (!(/[aeiouAEIOU]/).test(c)) c].join(''); // 'bcdf'
-var interpolatedZeros = [for (c of str) c + '0' ].join(''); // 'a0b0c0d0e0f0'
- -

Для предупреждения конвертации в число (в данном конкретном примере) использвалась функция {{jsxref("Array.prototype.join", "join()")}}.

- -

Примеры

- -

Простые сокращения

- -
[for (i of [ 1, 2, 3 ]) i*i ];
-// [ 1, 4, 9 ]
-
-var abc = [ "A", "B", "C" ];
-[for (letters of abc) letters.toLowerCase()];
-// [ "a", "b", "c" ]
- -

Сокращения с условным оператором "if"

- -
var years = [ 1954, 1974, 1990, 2006, 2010, 2014 ];
-[for (year of years) if (year > 2000) year];
-// [ 2006, 2010, 2014 ]
-[for (year of years) if (year > 2000) if(year < 2010) year];
-// [ 2006], the same as below:
-[for (year of years) if (year > 2000 && year < 2010) year];
-// [ 2006]
-
- -

Сокращения в сравнении с map и filter

- -

Простой способ понять синтаксис Array Comprehension - это сравнить его с методами Array {{jsxref("Array.map", "map")}} и {{jsxref("Array.filter", "filter")}}:

- -
var numbers = [ 1, 2, 3 ];
-
-numbers.map(function (i) { return i * i });
-numbers.map(i => i*i);
-[for (i of numbers) i*i ];
-// all are [ 1, 4, 9 ]
-
-numbers.filter(function (i) { return i < 3 });
-numbers.filter(i => i < 3);
-[for (i of numbers) if (i < 3) i];
-// all are [ 1, 2 ]
-
- -

Сокращения с двумя массивами

- -

Использование двух итераторов for-of для работы с двумя массивами:

- -
var numbers = [ 1, 2, 3 ];
-var letters = [ "a", "b", "c" ];
-
-var cross = [for (i of numbers) for (j of letters) i+j];
-// [ "1a", "1b", "1c", "2a", "2b", "2c", "3a", "3b", "3c" ]
-
-var grid = [for (i of numbers) [for (j of letters) i+j]];
-// [
-//  ["1a", "1b", "1c"],
-//  ["2a", "2b", "2c"],
-//  ["3a", "3b", "3c"]
-// ]
-
-[for (i of numbers) if (i > 1) for (j of letters) if(j > "a") i+j]
-// ["2b", "2c", "3b", "3c"], the same as below:
-
-[for (i of numbers) for (j of letters) if (i > 1) if(j > "a") i+j]
-// ["2b", "2c", "3b", "3c"]
-
-[for (i of numbers) if (i > 1) [for (j of letters) if(j > "a") i+j]]
-// [["2b", "2c"], ["3b", "3c"]], not the same as below:
-
-[for (i of numbers) [for (j of letters) if (i > 1) if(j > "a") i+j]]
-// [[], ["2b", "2c"], ["3b", "3c"]]
-
- -

Спецификации

- -

Изначально было в черновике ECMAScript 2015, но исключено в ревизии 27 (Август 2014). Смотрите старые ревизии ES2015 для уточнения семантики.

- -

Совместимость с браузерами

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка{{CompatNo}}{{ CompatGeckoDesktop("30") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("30") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Специфика работы SpiderMonkey

- - - -

Отличия от старой версии JS1.7/JS1.8

- -
Сокращения из JS1.7/JS1.8 были исключены из движка Gecko, начиная с версии 46 ({{bug(1220564)}}).
- -

Старый синтаксис (не используйте его больше!):

- -
[X for (Y in Z)]
-[X for each (Y in Z)]
-[X for (Y of Z)]
- -

Различия:

- - - -

Смотрите Bug 1220564, comment 42 для внесения предложений по коду.

- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/operators/expression_closures/index.html b/files/ru/web/javascript/reference/operators/expression_closures/index.html deleted file mode 100644 index 9c8f613699..0000000000 --- a/files/ru/web/javascript/reference/operators/expression_closures/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: Expression closures -slug: Web/JavaScript/Reference/Operators/Expression_closures -tags: - - Нестандартная - - Функции -translation_of: Archive/Web/JavaScript/Expression_closures ---- -
Не является стандартом. Не используйте данный синтаксис!
-Синтаксис замкнутого выражения является устаревшей возможностью SpiderMonkey и будет удален. Используйте вместо него стрелочные функции.
- -
{{jsSidebar("Operators")}}
- -

Замкнутые выражения – это синтаксис для удобной записи коротких и простых функций.

- -

Синтаксис

- -
function [name]([param1[, param2[, ..., paramN]]])
-   expression
-
- -

Параметры

- -
-
name
-
Имя функции. Может быть пропущено, в таком случае функция будет являться анонимной. Имя функции доступно только в теле функции.
-
paramN
-
Имя аргумента, передаваемого функции. Всего может быть передано вплоть до 255 аргументов.
-
expression
-
Выражение, содержащее тело функции.
-
- -

Описание

- -

Этот функционал – ничто иное как короткая нотация для записи простых функций. Он призван добавить в язык нечто похожее на Лямбда-исчисления.

- -

JavaScript 1.7 и старше:

- -
function(x) { return x * x; }
- -

JavaScript 1.8:

- -
function(x) x * x
- -

Такой синтаксис позволяет отбросить фигурные скобки и оператор return. Данный подход, кроме краткости записи, иных преимуществ не имеет.

- -

Примеры использования

- -

Короткая запись для привязки слушателей событий:

- -
 document.addEventListener("click", function() false, true);
-
- -

Использование такой записи для работы с функциями массивов из JavaScript 1.6:

- -
elems.some(function(elem) elem.type == "text");
-
- -

Таблица совместимости

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

 

- -

Смотрите также

- - diff --git a/files/ru/web/javascript/reference/operators/generator_comprehensions/index.html b/files/ru/web/javascript/reference/operators/generator_comprehensions/index.html deleted file mode 100644 index fb04526d8a..0000000000 --- a/files/ru/web/javascript/reference/operators/generator_comprehensions/index.html +++ /dev/null @@ -1,229 +0,0 @@ ---- -title: Упрощенный синтаксис создания функций-генераторов -slug: Web/JavaScript/Reference/Operators/Generator_comprehensions -tags: - - Итераторы -translation_of: Archive/Web/JavaScript/Generator_comprehensions ---- -
Не в стандарте. Не используйте!
-Включения генераторов - нестандартная возможность, и вряд ли когда-либо появится в ECMAScript. В будущем попробуйте использовать {{jsxref("Statements/function*", "generator", "", 1)}}.
- -
{{jsSidebar("Operators")}}
- -
Синтаксис включений генераторов - это выражение, которое позволяет быстро создать новую функцию-генератор из существующего итератора. Включения присутствуют во множестве языков программирования.
- -
 
- -
Ниже показаны отличия от старого синтаксиса генераторных выражений в SpiderMonkey, основанных на предложениях к стандарту ECMAScript 4.
- -
 
- -

Синтаксис

- -
(for (x of iterable) x)
-(for (x of iterable) if (condition) x)
-(for (x of iterable) for (y of iterable) x + y)
-
- -

Описание

- -

Внутри включений генераторов допустимы два типа компонентов:

- - - -

Конструкция for-of всегда идёт первой. Таких конструкций может быть несколько.

- -

Существенный недостаток {{jsxref("Operators/Array_comprehensions","включений массивов","","true")}} - это то, что они создают полносью новый массив в памяти. Даже когда исходный массив небольшой, накладные расходы получаются весьма заметными, а уж когда входные данные - это большой массив или дорогой (или бесконечный) генератор, создание нового массива может быть трудной задачей.

- -

Генераторы позволяют выполнять ленивые вычисления последовательностей, то есть рассчитывать данные только тогда, когда они нужны. Синтаксисы включений генераторов и включений массивов практически аналогичны — первые используют () вместо [] — но вместо массива они создают генератор, который может выполняться лениво. Включения генераторов можно считать просто более кратким способом создания генераторов.

- -

Предположим, у нас есть итератор it, который итерирует по длинной последовательности чисел. Мы хотим создать новый итератор, который будет итерировать по тем же числам, умноженным на два. Включение массивов создало бы в памяти новый массив с умноженными числами:

- -
var doubles = [for (i in it) i * 2];
-
- -

А включение генераторов создало бы новый итератор, который высчитывал бы  следующее умноженное значение, когда оно нужно:

- -
var it2 = (for (i in it) i * 2);
-console.log(it2.next()); // Первое значение из it, умноженное на два
-console.log(it2.next()); // Второе значение из it, умноженное на два
-
- -

Когда включение генераторов передаётся как аргумент функции, можно обойтись без скобок вокруг включения:

- -
var result = doSomething(for (i in it) i * 2);
-
- -

Эти два примера отличаются тем, что используя включения генераторов, нам нужно пройтись по структуре объекта только однажды, а используя включения массивов - дважды: сначала при создании включения, затем, при самой итерации.

- -

Примеры

- -

Простое включение генераторов

- -
(for (i of [ 1, 2, 3 ]) i*i );
-// Функция-генератор, которая отдаёт 1, 4, 9 и так далее
-
-[...(for (i of [ 1, 2, 3 ]) i*i )];
-// [1, 4, 9]
-
-var abc = [ "A", "B", "C" ];
-(for (letters of abc) letters.toLowerCase());
-// Функция-генератор, которая отдаёт 'a', 'b' и 'c'
-
- -

Включение генераторов с условием

- -
var years = [ 1954, 1974, 1990, 2006, 2010, 2014 ];
-
-(for (year of years) if (year > 2000) year);
-// функция-генератор, которая отдаёт 2006, 2010 и 2014
-
-(for (year of years) if (year > 2000) if(year < 2010) year);
-// функция-генератор, которая отдаёт 2006, как и функция ниже:
-
-(for (year of years) if (year > 2000 && year < 2010) year);
-// функция-генератор, которая отдаёт 2006
-
- -

Включение генератора в сравнении с функцией-генератором

- -

Будет проще понять синтаксис включений генераторов, если сравнить его с функцией-генератором.

- -

Пример 1: Простой генератор.

- -
var numbers = [ 1, 2, 3 ];
-
-// Функция-генератор
-(function*() {
-  for (let i of numbers) {
-    yield i * i;
-  }
-})()
-
-// Включение генератора
-(for (i of numbers) i*i );
-
-// Результат: в обоих случаях получается генератор, который отдаёт [ 1, 4, 9 ]
-
- -

Пример 2: Использование if в генераторе.

- -
var numbers = [ 1, 2, 3 ];
-
-// Функция-генератор
-(function*() {
-  for (let i of numbers) {
-    if (i < 3) {
-      yield i * 1;
-    }
-  }
-})()
-
-// Включение генератора
-(for (i of numbers) if (i < 3) i);
-
-// Результат: в обоих случаях получается генератор, который отдаёт [ 1, 2 ]
- -

Спецификации

- -

Включения генераторов изначально входили в черновик ECMAScript 6, но их убрали в ревизии 27 (August 2014). Please see older revisions of ES6 for specification semantics.

- -

Поддержка браузерами

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Начальная поддержка{{CompatNo}}{{ CompatGeckoDesktop("30") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Начальная поддержка{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("30") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Особенности реализации в SpiderMonkey

- - - -

Отличия от старых JS1.7/JS1.8 включений

- -
JS1.7/JS1.8 включения убраны из Gecko 46 ({{bug(1220564)}}).
- -

Старый синтаксис включений (не используйте!):

- -
(X for (Y in Z))
-(X for each (Y in Z))
-(X for (Y of Z))
-
- -

Отличия:

- - - -

См. также

- - diff --git a/files/ru/web/javascript/reference/statements/for_each...in/index.html b/files/ru/web/javascript/reference/statements/for_each...in/index.html deleted file mode 100644 index c609f436c0..0000000000 --- a/files/ru/web/javascript/reference/statements/for_each...in/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: for each...in -slug: Web/JavaScript/Reference/Statements/for_each...in -translation_of: Archive/Web/JavaScript/for_each...in ---- -
{{jsSidebar("Statements")}}
- -
-

Конструкция for each...in заявлена как "deprecated", как часть стандарта ECMA-357 (E4X). Поддержка E4X была удалена. Вместо for each...in рассмотрите использование for...of. (Пожалуйста обратите внимание: {{ bug("791343")}}.)
-
- Firefox теперь предупреждает об использовании for each...in и for each...in удаляется из ночных сборок. Пожалуйста, посмотрите Warning: JavaScript 1.6's for-each-in loops are deprecated для помощи в миграции.

-
- -

Выражение for each...in выполняет перебор свойств указанного объекта. Для каждого свойства выполняется указанный оператор.

- -

Синтаксис

- -
for each (variable in object) {
-  statement
-}
- -
-
variable
-
Variable to iterate over property values, optionally declared with the var keyword. This variable is local to the function, not to the loop.
-
- -
-
object
-
Object for which the properties are iterated.
-
- -
-
statement
-
A statement to execute for each property. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements.
-
- -

Description

- -

Some built-in properties are not iterated over. These include all built-in methods of objects, e.g. String's indexOf method. However, all user-defined properties are iterated over.

- -

Examples

- -

Using for each...in

- -

Warning: Never use a loop like this on arrays. Only use it on objects. See for...in for more details.

- -

The following snippet iterates over an object's properties, calculating their sum:

- -
var sum = 0;
-var obj = {prop1: 5, prop2: 13, prop3: 8};
-
-for each (var item in obj) {
-  sum += item;
-}
-
-console.log(sum); // logs "26", which is 5+13+8
- -

Specifications

- -

Not part of a current ECMA-262 specification. Implemented in JavaScript 1.6 and deprecated.

- -

Браузерная совместимость

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop("1.8")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("1.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Firefox specific note

- - - -

Смотрите также

- - -- cgit v1.2.3-54-g00ecf