From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../a_re-introduction_to_javascript/index.html | 951 --------------------- .../control_flow_and_error_handling/index.html | 425 --------- .../guide/details_of_the_object_model/index.html | 719 ---------------- files/fa/web/javascript/guide/functions/index.html | 649 -------------- .../javascript/guide/grammar_and_types/index.html | 674 --------------- files/fa/web/javascript/guide/index.html | 108 --- .../web/javascript/guide/introduction/index.html | 139 --- files/fa/web/javascript/index.html | 128 --- .../inheritance_and_the_prototype_chain/index.html | 533 ------------ .../fa/web/javascript/reference/classes/index.html | 418 --------- .../fa/web/javascript/reference/errors/index.html | 31 - .../reference/errors/too_much_recursion/index.html | 114 --- .../reference/errors/unexpected_token/index.html | 84 -- .../web/javascript/reference/functions/index.html | 596 ------------- .../reference/global_objects/array/index.html | 464 ---------- .../reference/global_objects/array/of/index.html | 102 --- .../global_objects/array/reduce/index.html | 579 ------------- .../reference/global_objects/function/index.html | 156 ---- .../javascript/reference/global_objects/index.html | 128 --- .../reference/global_objects/null/index.html | 126 --- .../reference/global_objects/regexp/index.html | 597 ------------- .../global_objects/regexp/test/index.html | 123 --- .../reference/global_objects/set/index.html | 459 ---------- files/fa/web/javascript/reference/index.html | 50 -- .../web/javascript/reference/operators/index.html | 302 ------- .../web/javascript/reference/statements/index.html | 131 --- 26 files changed, 8786 deletions(-) delete mode 100644 files/fa/web/javascript/a_re-introduction_to_javascript/index.html delete mode 100644 files/fa/web/javascript/guide/control_flow_and_error_handling/index.html delete mode 100644 files/fa/web/javascript/guide/details_of_the_object_model/index.html delete mode 100644 files/fa/web/javascript/guide/functions/index.html delete mode 100644 files/fa/web/javascript/guide/grammar_and_types/index.html delete mode 100644 files/fa/web/javascript/guide/index.html delete mode 100644 files/fa/web/javascript/guide/introduction/index.html delete mode 100644 files/fa/web/javascript/index.html delete mode 100644 files/fa/web/javascript/inheritance_and_the_prototype_chain/index.html delete mode 100644 files/fa/web/javascript/reference/classes/index.html delete mode 100644 files/fa/web/javascript/reference/errors/index.html delete mode 100644 files/fa/web/javascript/reference/errors/too_much_recursion/index.html delete mode 100644 files/fa/web/javascript/reference/errors/unexpected_token/index.html delete mode 100644 files/fa/web/javascript/reference/functions/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/array/reduce/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/null/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/regexp/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/regexp/test/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/set/index.html delete mode 100644 files/fa/web/javascript/reference/index.html delete mode 100644 files/fa/web/javascript/reference/operators/index.html delete mode 100644 files/fa/web/javascript/reference/statements/index.html (limited to 'files/fa/web/javascript') diff --git a/files/fa/web/javascript/a_re-introduction_to_javascript/index.html b/files/fa/web/javascript/a_re-introduction_to_javascript/index.html deleted file mode 100644 index 4811a5e430..0000000000 --- a/files/fa/web/javascript/a_re-introduction_to_javascript/index.html +++ /dev/null @@ -1,951 +0,0 @@ ---- -title: A re-introduction to JavaScript (JS tutorial) -slug: Web/JavaScript/A_re-introduction_to_JavaScript -translation_of: Web/JavaScript/A_re-introduction_to_JavaScript ---- -
{{jsSidebar}}
- -

چرا دوباره معرفی شود؟ زیرا جاوااسکریپت از لحاظ ایجاد سوتفاهم در جهان مشهور است. این اغلب به عنوان یک اسباب بازی مورد تمسخر قرار می گیرد ، اما در زیر لایه ساده فریبنده آن ، ویژگی های قدرتمند زبان در انتظار است. جاوا اسکریپت اکنون توسط تعداد باورنکردنی از برنامه های با مشخصات بالا استفاده می شود ، نشان می دهد که دانش عمیق تر از این فن آوری مهارت مهمی برای هر توسعه دهنده وب یا تلفن همراه است.

- -

It's useful to start with an overview of the language's history. JavaScript was created in 1995 by Brendan Eich while he was an engineer at Netscape. JavaScript was first released with Netscape 2 early in 1996. It was originally going to be called LiveScript, but it was renamed in an ill-fated marketing decision that attempted to capitalize on the popularity of Sun Microsystem's Java language — despite the two having very little in common. This has been a source of confusion ever since.

- -

Several months later, Microsoft released JScript with Internet Explorer 3. It was a mostly-compatible JavaScript work-alike. Several months after that, Netscape submitted JavaScript to Ecma International, a European standards organization, which resulted in the first edition of the ECMAScript standard that year. The standard received a significant update as ECMAScript edition 3 in 1999, and it has stayed pretty much stable ever since. The fourth edition was abandoned, due to political differences concerning language complexity. Many parts of the fourth edition formed the basis for ECMAScript edition 5, published in December of 2009, and for the 6th major edition of the standard, published in June of 2015.

- -
-

Because it is more familiar, we will refer to ECMAScript as "JavaScript" from this point on.

-
- -

Unlike most programming languages, the JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world. The most common host environment is the browser, but JavaScript interpreters can also be found in a huge list of other places, including Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo's Widget engine, server-side environments such as Node.js, NoSQL databases like the open source Apache CouchDB, embedded computers, complete desktop environments like GNOME (one of the most popular GUIs for GNU/Linux operating systems), and others.

- -

Overview

- -

JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes, instead of classes (see more about prototypical inheritance and ES2015 classes). JavaScript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object.

- -

Let's start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript's types are:

- - - -

... oh, and {{jsxref("undefined")}} and {{jsxref("null")}}, which are ... slightly odd. And {{jsxref("Array")}}, which is a special kind of object. And {{jsxref("Date")}} and {{jsxref("RegExp")}}, which are objects that you get for free. And to be technically accurate, functions are just a special type of object. So the type diagram looks more like this:

- - - -

And there are some built-in {{jsxref("Error")}} types as well. Things are a lot easier if we stick with the first diagram, however, so we'll discuss the types listed there for now.

- -

Numbers

- -

Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values", according to the spec —  There's no such thing as an integer in JavaScript (except {{jsxref("BigInt")}}), so you have to be a little careful. See this example:

- -
console.log(3 / 2);             // 1.5, not 1
-console.log(Math.floor(3 / 2)); // 1
- -

So an apparent integer is in fact implicitly a float.

- -

Also, watch out for stuff like:

- -
0.1 + 0.2 == 0.30000000000000004;
-
- -

In practice, integer values are treated as 32-bit ints, and some implementations even store it that way until they are asked to perform an instruction that's valid on a Number but not on a 32-bit integer. This can be important for bit-wise operations.

- -

The standard arithmetic operators are supported, including addition, subtraction, modulus (or remainder) arithmetic, and so forth. There's also a built-in object that we did not mention earlier called {{jsxref("Math")}} that provides advanced mathematical functions and constants:

- -
Math.sin(3.5);
-var circumference = 2 * Math.PI * r;
-
- -

You can convert a string to an integer using the built-in {{jsxref("Global_Objects/parseInt", "parseInt()")}} function. This takes the base for the conversion as an optional second argument, which you should always provide:

- -
parseInt('123', 10); // 123
-parseInt('010', 10); // 10
-
- -

In older browsers, strings beginning with a "0" are assumed to be in octal (radix 8), but this hasn't been the case since 2013 or so. Unless you're certain of your string format, you can get surprising results on those older browsers:

- -
parseInt('010');  //  8
-parseInt('0x10'); // 16
-
- -

Here, we see the {{jsxref("Global_Objects/parseInt", "parseInt()")}} function treat the first string as octal due to the leading 0, and the second string as hexadecimal due to the leading "0x". The hexadecimal notation is still in place; only octal has been removed.

- -

If you want to convert a binary number to an integer, just change the base:

- -
parseInt('11', 2); // 3
-
- -

Similarly, you can parse floating point numbers using the built-in {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} function. Unlike its {{jsxref("Global_Objects/parseInt", "parseInt()")}} cousin, parseFloat() always uses base 10.

- -

You can also use the unary + operator to convert values to numbers:

- -
+ '42';   // 42
-+ '010';  // 10
-+ '0x10'; // 16
-
- -

A special value called {{jsxref("NaN")}} (short for "Not a Number") is returned if the string is non-numeric:

- -
parseInt('hello', 10); // NaN
-
- -

NaN is toxic: if you provide it as an operand to any mathematical operation, the result will also be NaN:

- -
NaN + 5; // NaN
-
- -

You can test for NaN using the built-in {{jsxref("Global_Objects/isNaN", "isNaN()")}} function:

- -
isNaN(NaN); // true
-
- -

JavaScript also has the special values {{jsxref("Infinity")}} and -Infinity:

- -
 1 / 0; //  Infinity
--1 / 0; // -Infinity
-
- -

You can test for Infinity, -Infinity and NaN values using the built-in {{jsxref("Global_Objects/isFinite", "isFinite()")}} function:

- -
isFinite(1 / 0); // false
-isFinite(-Infinity); // false
-isFinite(NaN); // false
-
- -
The {{jsxref("Global_Objects/parseInt", "parseInt()")}} and {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.
- -

Strings

- -

Strings in JavaScript are sequences of Unicode characters. This should be welcome news to anyone who has had to deal with internationalization. More accurately, they are sequences of UTF-16 code units; each code unit is represented by a 16-bit number. Each Unicode character is represented by either 1 or 2 code units.

- -

If you want to represent a single character, you just use a string consisting of that single character.

- -

To find the length of a string (in code units), access its length property:

- -
'hello'.length; // 5
-
- -

There's our first brush with JavaScript objects! Did we mention that you can use strings like {{jsxref("Object", "objects", "", 1)}} too? They have {{jsxref("String", "methods", "#Methods", 1)}} as well that allow you to manipulate the string and access information about the string:

- -
'hello'.charAt(0); // "h"
-'hello, world'.replace('world', 'mars'); // "hello, mars"
-'hello'.toUpperCase(); // "HELLO"
-
- -

Other types

- -

JavaScript distinguishes between {{jsxref("null")}}, which is a value that indicates a deliberate non-value (and is only accessible through the null keyword), and {{jsxref("undefined")}}, which is a value of type undefined that indicates an uninitialized variable — that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is undefined. undefined is actually a constant.

- -

JavaScript has a boolean type, with possible values true and false (both of which are keywords.) Any value can be converted to a boolean according to the following rules:

- -
    -
  1. false, 0, empty strings (""), NaN, null, and undefined all become false.
  2. -
  3. All other values become true.
  4. -
- -

You can perform this conversion explicitly using the Boolean() function:

- -
Boolean('');  // false
-Boolean(234); // true
-
- -

However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an if statement (see below). For this reason, we sometimes speak simply of "true values" and "false values," meaning values that become true and false, respectively, when converted to booleans. Alternatively, such values can be called "truthy" and "falsy", respectively.

- -

Boolean operations such as && (logical and), || (logical or), and ! (logical not) are supported; see below.

- -

Variables

- -

New variables in JavaScript are declared using one of three keywords: let, const, or var.
-
- let allows you to declare block-level variables. The declared variable is available from the block it is enclosed in.

- -
let a;
-let name = 'Simon';
-
- -

The following is an example of scope with a variable declared with let:

- -
// myLetVariable is *not* visible out here
-
-for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {
-  // myLetVariable is only visible in here
-}
-
-// myLetVariable is *not* visible out here
-
-
- -

const allows you to declare variables whose values are never intended to change. The variable is available from the block it is declared in.

- -
const Pi = 3.14; // variable Pi is set
-Pi = 1; // will throw an error because you cannot change a constant variable.
- -


- var is the most common declarative keyword. It does not have the restrictions that the other two keywords have. This is because it was traditionally the only way to declare a variable in JavaScript. A variable declared with the var keyword is available from the function it is declared in.

- -
var a;
-var name = 'Simon';
- -

An example of scope with a variable declared with var:

- -
// myVarVariable *is* visible out here
-
-for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) {
-  // myVarVariable is visible to the whole function
-}
-
-// myVarVariable *is* visible out here
-
- -

If you declare a variable without assigning any value to it, its type is undefined.

- -

An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have a scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function. However, starting with ECMAScript 2015, let and const declarations allow you to create block-scoped variables.

- -

Operators

- -

JavaScript's numeric operators are +, -, *, / and % which is the remainder operator (which is the same as modulo.) Values are assigned using =, and there are also compound assignment statements such as += and -=. These extend out to x = x operator y.

- -
x += 5;
-x = x + 5;
-
- -

You can use ++ and -- to increment and decrement respectively. These can be used as a prefix or postfix operators.

- -

The + operator also does string concatenation:

- -
'hello' + ' world'; // "hello world"
-
- -

If you add a string to a number (or other value) everything is converted into a string first. This might trip you up:

- -
'3' + 4 + 5;  // "345"
- 3 + 4 + '5'; // "75"
-
- -

Adding an empty string to something is a useful way of converting it to a string itself.

- -

Comparisons in JavaScript can be made using <, >, <= and >=. These work for both strings and numbers. Equality is a little less straightforward. The double-equals operator performs type coercion if you give it different types, with sometimes interesting results:

- -
123 == '123'; // true
-1 == true; // true
-
- -

To avoid type coercion, use the triple-equals operator:

- -
123 === '123'; // false
-1 === true;    // false
-
- -

There are also != and !== operators.

- -

JavaScript also has bitwise operations. If you want to use them, they're there.

- -

Control structures

- -

JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by if and else; you can chain them together if you like:

- -
var name = 'kittens';
-if (name == 'puppies') {
-  name += ' woof';
-} else if (name == 'kittens') {
-  name += ' meow';
-} else {
-  name += '!';
-}
-name == 'kittens meow';
-
- -

JavaScript has while loops and do-while loops. The first is good for basic looping; the second for loops where you wish to ensure that the body of the loop is executed at least once:

- -
while (true) {
-  // an infinite loop!
-}
-
-var input;
-do {
-  input = get_input();
-} while (inputIsNotValid(input));
-
- -

JavaScript's for loop is the same as that in C and Java: it lets you provide the control information for your loop on a single line.

- -
for (var i = 0; i < 5; i++) {
-  // Will execute 5 times
-}
-
- -

JavaScript also contains two other prominent for loops: for...of

- -
for (let value of array) {
-  // do something with value
-}
-
- -

and for...in:

- -
for (let property in object) {
-  // do something with object property
-}
-
- -

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:

- -
var name = o && o.getName();
-
- -

Or for caching values (when falsy values are invalid):

- -
var name = cachedName || (cachedName = getName());
-
- -

JavaScript has a ternary operator for conditional expressions:

- -
var allowed = (age > 18) ? 'yes' : 'no';
-
- -

The switch statement can be used for multiple branches based on a number or string:

- -
switch (action) {
-  case 'draw':
-    drawIt();
-    break;
-  case 'eat':
-    eatIt();
-    break;
-  default:
-    doNothing();
-}
-
- -

If you don't add a break statement, execution will "fall through" to the next level. This is very rarely what you want — in fact it's worth specifically labeling deliberate fallthrough with a comment if you really meant it to aid debugging:

- -
switch (a) {
-  case 1: // fallthrough
-  case 2:
-    eatIt();
-    break;
-  default:
-    doNothing();
-}
-
- -

The default clause is optional. You can have expressions in both the switch part and the cases if you like; comparisons take place between the two using the === operator:

- -
switch (1 + 3) {
-  case 2 + 2:
-    yay();
-    break;
-  default:
-    neverhappens();
-}
-
- -

Objects

- -

JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to:

- - - -

The fact that this data structure is so widely used is a testament to its versatility. Since everything (bar core types) in JavaScript is an object, any JavaScript program naturally involves a great deal of hash table lookups. It's a good thing they're so fast!

- -

The "name" part is a JavaScript string, while the value can be any JavaScript value — including more objects. This allows you to build data structures of arbitrary complexity.

- -

There are two basic ways to create an empty object:

- -
var obj = new Object();
-
- -

And:

- -
var obj = {};
-
- -

These are semantically equivalent; the second is called object literal syntax and is more convenient. This syntax is also the core of JSON format and should be preferred at all times.

- -

Object literal syntax can be used to initialize an object in its entirety:

- -
var obj = {
-  name: 'Carrot',
-  for: 'Max', // 'for' is a reserved word, use '_for' instead.
-  details: {
-    color: 'orange',
-    size: 12
-  }
-};
-
- -

Attribute access can be chained together:

- -
obj.details.color; // orange
-obj['details']['size']; // 12
-
- -

The following example creates an object prototype(Person) and an instance of that prototype(you).

- -
function Person(name, age) {
-  this.name = name;
-  this.age = age;
-}
-
-// Define an object
-var you = new Person('You', 24);
-// We are creating a new person named "You" aged 24.
-
-
- -

Once created, an object's properties can again be accessed in one of two ways:

- -
// dot notation
-obj.name = 'Simon';
-var name = obj.name;
-
- -

And...

- -
// bracket notation
-obj['name'] = 'Simon';
-var name = obj['name'];
-// can use a variable to define a key
-var user = prompt('what is your key?')
-obj[user] = prompt('what is its value?')
-
- -

These are also semantically equivalent. The second method has the advantage that the name of the property is provided as a string, which means it can be calculated at run-time. However, using this method prevents some JavaScript engine and minifier optimizations being applied. It can also be used to set and get properties with names that are reserved words:

- -
obj.for = 'Simon'; // Syntax error, because 'for' is a reserved word
-obj['for'] = 'Simon'; // works fine
-
- -
-

Starting in ECMAScript 5, reserved words may be used as object property names "in the buff". This means that they don't need to be "clothed" in quotes when defining object literals. See the ES5 Spec.

-
- -

For more on objects and prototypes see Object.prototype. For an explanation of object prototypes and the object prototype chains see Inheritance and the prototype chain.

- -
-

Starting in ECMAScript 2015, object keys can be defined by the variable using bracket notation upon being created. {[phoneType]: 12345} is possible instead of just var userPhone = {}; userPhone[phoneType] = 12345.

-
- -

Arrays

- -

Arrays in JavaScript are actually a special type of object. They work very much like regular objects (numerical properties can naturally be accessed only using [] syntax) but they have one magic property called 'length'. This is always one more than the highest index in the array.

- -

One way of creating arrays is as follows:

- -
var a = new Array();
-a[0] = 'dog';
-a[1] = 'cat';
-a[2] = 'hen';
-a.length; // 3
-
- -

A more convenient notation is to use an array literal:

- -
var a = ['dog', 'cat', 'hen'];
-a.length; // 3
-
- -

Note that array.length isn't necessarily the number of items in the array. Consider the following:

- -
var a = ['dog', 'cat', 'hen'];
-a[100] = 'fox';
-a.length; // 101
-
- -

Remember — the length of the array is one more than the highest index.

- -

If you query a non-existent array index, you'll get a value of undefined in return:

- -
typeof a[90]; // undefined
-
- -

If you take the above about [] and length into account, you can iterate over an array using the following for loop:

- -
for (var i = 0; i < a.length; i++) {
-  // Do something with a[i]
-}
-
- -

ES2015 introduced the more concise for...of loop for iterable objects such as arrays:

- -
for (const currentValue of a) {
-  // Do something with currentValue
-}
- -

You could also iterate over an array using a for...in loop, however this does not iterate over the array elements, but the array indices. Furthermore, if someone added new properties to Array.prototype, they would also be iterated over by such a loop. Therefore this loop type is not recommended for arrays.

- -

Another way of iterating over an array that was added with ECMAScript 5 is forEach():

- -
['dog', 'cat', 'hen'].forEach(function(currentValue, index, array) {
-  // Do something with currentValue or array[index]
-});
-
- -

If you want to append an item to an array simply do it like this:

- -
a.push(item);
- -

Arrays come with a number of methods. See also the full documentation for array methods.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Method nameDescription
a.toString()Returns a string with the toString() of each element separated by commas.
a.toLocaleString()Returns a string with the toLocaleString() of each element separated by commas.
a.concat(item1[, item2[, ...[, itemN]]])Returns a new array with the items added on to it.
a.join(sep)Converts the array to a string — with values delimited by the sep param
a.pop()Removes and returns the last item.
a.push(item1, ..., itemN)Appends items to the end of the array.
a.shift()Removes and returns the first item.
a.unshift(item1[, item2[, ...[, itemN]]])Prepends items to the start of the array.
a.slice(start[, end])Returns a sub-array.
a.sort([cmpfn])Takes an optional comparison function.
a.splice(start, delcount[, item1[, ...[, itemN]]])Lets you modify an array by deleting a section and replacing it with more items.
a.reverse()Reverses the array.
- -

Functions

- -

Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:

- -
function add(x, y) {
-  var total = x + y;
-  return total;
-}
-
- -

This demonstrates a basic function. A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

- -

The named parameters turn out to be more like guidelines than anything else. You can call a function without passing the parameters it expects, in which case they will be set to undefined.

- -
add(); // NaN
-// You can't perform addition on undefined
-
- -

You can also pass in more arguments than the function is expecting:

- -
add(2, 3, 4); // 5
-// added the first two; 4 was ignored
-
- -

That may seem a little silly, but functions have access to an additional variable inside their body called arguments, which is an array-like object holding all of the values passed to the function. Let's re-write the add function to take as many values as we want:

- -
function add() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum;
-}
-
-add(2, 3, 4, 5); // 14
-
- -

That's really not any more useful than writing 2 + 3 + 4 + 5 though. Let's create an averaging function:

- -
function avg() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum / arguments.length;
-}
-
-avg(2, 3, 4, 5); // 3.5
-
- -

This is pretty useful, but it does seem a little verbose. To reduce this code a bit more we can look at substituting the use of the arguments array through Rest parameter syntax. In this way, we can pass in any number of arguments into the function while keeping our code minimal. The rest parameter operator is used in function parameter lists with the format: ...variable and it will include within that variable the entire list of uncaptured arguments that the function was called with. We will also replace the for loop with a for...of loop to return the values within our variable.

- -
function avg(...args) {
-  var sum = 0;
-  for (let value of args) {
-    sum += value;
-  }
-  return sum / args.length;
-}
-
-avg(2, 3, 4, 5); // 3.5
-
- -
In the above code, the variable args holds all the values that were passed into the function.
-
-It is important to note that wherever the rest parameter operator is placed in a function declaration it will store all arguments after its declaration, but not before. i.e. function avg(firstValue, ...args) will store the first value passed into the function in the firstValue variable and the remaining arguments in args. That's another useful language feature but it does lead us to a new problem. The avg() function takes a comma-separated list of arguments — but what if you want to find the average of an array? You could just rewrite the function as follows:
- -
function avgArray(arr) {
-  var sum = 0;
-  for (var i = 0, j = arr.length; i < j; i++) {
-    sum += arr[i];
-  }
-  return sum / arr.length;
-}
-
-avgArray([2, 3, 4, 5]); // 3.5
-
- -

But it would be nice to be able to reuse the function that we've already created. Luckily, JavaScript lets you call a function with an arbitrary array of arguments, using the {{jsxref("Function.apply", "apply()")}} method of any function object.

- -
avg.apply(null, [2, 3, 4, 5]); // 3.5
-
- -

The second argument to apply() is the array to use as arguments; the first will be discussed later on. This emphasizes the fact that functions are objects too.

- -
-

You can achieve the same result using the spread operator in the function call.

- -

For instance: avg(...numbers)

-
- -

JavaScript lets you create anonymous functions.

- -
var avg = function() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum / arguments.length;
-};
-
- -

This is semantically equivalent to the function avg() form. It's extremely powerful, as it lets you put a full function definition anywhere that you would normally put an expression. This enables all sorts of clever tricks. Here's a way of "hiding" some local variables — like block scope in C:

- -
var a = 1;
-var b = 2;
-
-(function() {
-  var b = 3;
-  a += b;
-})();
-
-a; // 4
-b; // 2
-
- -

JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.

- -
function countChars(elm) {
-  if (elm.nodeType == 3) { // TEXT_NODE
-    return elm.nodeValue.length;
-  }
-  var count = 0;
-  for (var i = 0, child; child = elm.childNodes[i]; i++) {
-    count += countChars(child);
-  }
-  return count;
-}
-
- -

This highlights a potential problem with anonymous functions: how do you call them recursively if they don't have a name? JavaScript lets you name function expressions for this. You can use named IIFEs (Immediately Invoked Function Expressions) as shown below:

- -
var charsInBody = (function counter(elm) {
-  if (elm.nodeType == 3) { // TEXT_NODE
-    return elm.nodeValue.length;
-  }
-  var count = 0;
-  for (var i = 0, child; child = elm.childNodes[i]; i++) {
-    count += counter(child);
-  }
-  return count;
-})(document.body);
-
- -

The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging.

- -

Note that JavaScript functions are themselves objects — like everything else in JavaScript — and you can add or change properties on them just like we've seen earlier in the Objects section.

- -

Custom objects

- -
For a more detailed discussion of object-oriented programming in JavaScript, see Introduction to Object-Oriented JavaScript.
- -

In classic Object Oriented Programming, objects are collections of data and methods that operate on that data. JavaScript is a prototype-based language that contains no class statement, as you'd find in C++ or Java (this is sometimes confusing for programmers accustomed to languages with a class statement). Instead, JavaScript uses functions as classes. Let's consider a person object with first and last name fields. There are two ways in which the name might be displayed: as "first last" or as "last, first". Using the functions and objects that we've discussed previously, we could display the data like this:

- -
function makePerson(first, last) {
-  return {
-    first: first,
-    last: last
-  };
-}
-function personFullName(person) {
-  return person.first + ' ' + person.last;
-}
-function personFullNameReversed(person) {
-  return person.last + ', ' + person.first;
-}
-
-var s = makePerson('Simon', 'Willison');
-personFullName(s); // "Simon Willison"
-personFullNameReversed(s); // "Willison, Simon"
-
- -

This works, but it's pretty ugly. You end up with dozens of functions in your global namespace. What we really need is a way to attach a function to an object. Since functions are objects, this is easy:

- -
function makePerson(first, last) {
-  return {
-    first: first,
-    last: last,
-    fullName: function() {
-      return this.first + ' ' + this.last;
-    },
-    fullNameReversed: function() {
-      return this.last + ', ' + this.first;
-    }
-  };
-}
-
-var s = makePerson('Simon', 'Willison');
-s.fullName(); // "Simon Willison"
-s.fullNameReversed(); // "Willison, Simon"
-
- -

Note on the this keyword. Used inside a function, this refers to the current object. What that actually means is specified by the way in which you called that function. If you called it using dot notation or bracket notation on an object, that object becomes this. If dot notation wasn't used for the call, this refers to the global object.

- -

Note that this is a frequent cause of mistakes. For example:

- -
var s = makePerson('Simon', 'Willison');
-var fullName = s.fullName;
-fullName(); // undefined undefined
-
- -

When we call fullName() alone, without using s.fullName(), this is bound to the global object. Since there are no global variables called first or last we get undefined for each one.

- -

We can take advantage of the this keyword to improve our makePerson function:

- -
function Person(first, last) {
-  this.first = first;
-  this.last = last;
-  this.fullName = function() {
-    return this.first + ' ' + this.last;
-  };
-  this.fullNameReversed = function() {
-    return this.last + ', ' + this.first;
-  };
-}
-var s = new Person('Simon', 'Willison');
-
- -

We have introduced another keyword: new. new is strongly related to this. It creates a brand new empty object, and then calls the function specified, with this set to that new object. Notice though that the function specified with this does not return a value but merely modifies the this object. It's new that returns the this object to the calling site. Functions that are designed to be called by new are called constructor functions. Common practice is to capitalize these functions as a reminder to call them with new.

- -

The improved function still has the same pitfall with calling fullName() alone.

- -

Our person objects are getting better, but there are still some ugly edges to them. Every time we create a person object we are creating two brand new function objects within it — wouldn't it be better if this code was shared?

- -
function personFullName() {
-  return this.first + ' ' + this.last;
-}
-function personFullNameReversed() {
-  return this.last + ', ' + this.first;
-}
-function Person(first, last) {
-  this.first = first;
-  this.last = last;
-  this.fullName = personFullName;
-  this.fullNameReversed = personFullNameReversed;
-}
-
- -

That's better: we are creating the method functions only once, and assigning references to them inside the constructor. Can we do any better than that? The answer is yes:

- -
function Person(first, last) {
-  this.first = first;
-  this.last = last;
-}
-Person.prototype.fullName = function() {
-  return this.first + ' ' + this.last;
-};
-Person.prototype.fullNameReversed = function() {
-  return this.last + ', ' + this.first;
-};
-
- -

Person.prototype is an object shared by all instances of Person. It forms part of a lookup chain (that has a special name, "prototype chain"): any time you attempt to access a property of Person that isn't set, JavaScript will check Person.prototype to see if that property exists there instead. As a result, anything assigned to Person.prototype becomes available to all instances of that constructor via the this object.

- -

This is an incredibly powerful tool. JavaScript lets you modify something's prototype at any time in your program, which means you can add extra methods to existing objects at runtime:

- -
var s = new Person('Simon', 'Willison');
-s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function
-
-Person.prototype.firstNameCaps = function() {
-  return this.first.toUpperCase();
-};
-s.firstNameCaps(); // "SIMON"
-
- -

Interestingly, you can also add things to the prototype of built-in JavaScript objects. Let's add a method to String that returns that string in reverse:

- -
var s = 'Simon';
-s.reversed(); // TypeError on line 1: s.reversed is not a function
-
-String.prototype.reversed = function() {
-  var r = '';
-  for (var i = this.length - 1; i >= 0; i--) {
-    r += this[i];
-  }
-  return r;
-};
-
-s.reversed(); // nomiS
-
- -

Our new method even works on string literals!

- -
'This can now be reversed'.reversed(); // desrever eb won nac sihT
-
- -

As mentioned before, the prototype forms part of a chain. The root of that chain is Object.prototype, whose methods include toString() — it is this method that is called when you try to represent an object as a string. This is useful for debugging our Person objects:

- -
var s = new Person('Simon', 'Willison');
-s.toString(); // [object Object]
-
-Person.prototype.toString = function() {
-  return '<Person: ' + this.fullName() + '>';
-}
-
-s.toString(); // "<Person: Simon Willison>"
-
- -

Remember how avg.apply() had a null first argument? We can revisit that now. The first argument to apply() is the object that should be treated as 'this'. For example, here's a trivial implementation of new:

- -
function trivialNew(constructor, ...args) {
-  var o = {}; // Create an object
-  constructor.apply(o, args);
-  return o;
-}
-
- -

This isn't an exact replica of new as it doesn't set up the prototype chain (it would be difficult to illustrate). This is not something you use very often, but it's useful to know about. In this snippet, ...args (including the ellipsis) is called the "rest arguments" — as the name implies, this contains the rest of the arguments.

- -

Calling

- -
var bill = trivialNew(Person, 'William', 'Orange');
- -

is therefore almost equivalent to

- -
var bill = new Person('William', 'Orange');
- -

apply() has a sister function named call, which again lets you set this but takes an expanded argument list as opposed to an array.

- -
function lastNameCaps() {
-  return this.last.toUpperCase();
-}
-var s = new Person('Simon', 'Willison');
-lastNameCaps.call(s);
-// Is the same as:
-s.lastNameCaps = lastNameCaps;
-s.lastNameCaps(); // WILLISON
-
- -

Inner functions

- -

JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier makePerson() function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:

- -
function parentFunc() {
-  var a = 1;
-
-  function nestedFunc() {
-    var b = 4; // parentFunc can't use this
-    return a + b;
-  }
-  return nestedFunc(); // 5
-}
-
- -

This provides a great deal of utility in writing more maintainable code. If a called function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside it. This keeps the number of functions that are in the global scope down, which is always a good thing.

- -

This is also a great counter to the lure of global variables. When writing complex code it is often tempting to use global variables to share values between multiple functions — which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together when it makes sense without polluting your global namespace — "local globals" if you like. This technique should be used with caution, but it's a useful ability to have.

- -

Closures

- -

This leads us to one of the most powerful abstractions that JavaScript has to offer — but also the most potentially confusing. What does this do?

- -
function makeAdder(a) {
-  return function(b) {
-    return a + b;
-  };
-}
-var add5 = makeAdder(5);
-var add20 = makeAdder(20);
-add5(6); // ?
-add20(7); // ?
-
- -

The name of the makeAdder() function should give it away: it creates new 'adder' functions, each of which, when called with one argument, adds it to the argument that it was created with.

- -

What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they do still exist — otherwise, the adder functions would be unable to work. What's more, there are two different "copies" of makeAdder()'s local variables — one in which a is 5 and the other one where a is 20. So the result of that function calls is as follows:

- -
add5(6); // returns 11
-add20(7); // returns 27
-
- -

Here's what's actually happening. Whenever JavaScript executes a function, a 'scope' object is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters. This is similar to the global object that all global variables and functions live in, but with a couple of important differences: firstly, a brand new scope object is created every time a function starts executing, and secondly, unlike the global object (which is accessible as this and in browsers as window) these scope objects cannot be directly accessed from your JavaScript code. There is no mechanism for iterating over the properties of the current scope object, for example.

- -

So when makeAdder() is called, a scope object is created with one property: a, which is the argument passed to the makeAdder() function. makeAdder() then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope object created for makeAdder() at this point, but the returned function maintains a reference back to that scope object. As a result, the scope object will not be garbage-collected until there are no more references to the function object that makeAdder() returned.

- -

Scope objects form a chain called the scope chain, similar to the prototype chain used by JavaScript's object system.

- -

A closure is the combination of a function and the scope object in which it was created. Closures let you save state — as such, they can often be used in place of objects. You can find several excellent introductions to closures.

diff --git a/files/fa/web/javascript/guide/control_flow_and_error_handling/index.html b/files/fa/web/javascript/guide/control_flow_and_error_handling/index.html deleted file mode 100644 index 9d9f2db887..0000000000 --- a/files/fa/web/javascript/guide/control_flow_and_error_handling/index.html +++ /dev/null @@ -1,425 +0,0 @@ ---- -title: Control flow and error handling -slug: Web/JavaScript/Guide/Control_flow_and_error_handling -translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling -original_slug: Web/JavaScript/راهنما/Control_flow_and_error_handling ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
- -

JavaScript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. This chapter provides an overview of these statements.

- -

The JavaScript reference contains exhaustive details about the statements in this chapter. The semicolon (;) character is used to separate statements in JavaScript code.

- -

Any JavaScript expression is also a statement. See Expressions and operators for complete information about expressions.

- -

Block statement

- -

The most basic statement is a block statement that is used to group statements. The block is delimited by a pair of curly brackets:

- -
{
-  statement_1;
-  statement_2;
-  .
-  .
-  .
-  statement_n;
-}
-
- -

Example

- -

Block statements are commonly used with control flow statements (e.g. if, for, while).

- -
while (x < 10) {
-  x++;
-}
-
- -

Here, { x++; } is the block statement.

- -

Important: JavaScript prior to ECMAScript2015 does not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not define a scope. "Standalone" blocks in JavaScript can produce completely different results from what they would produce in C or Java. For example:

- -
var x = 1;
-{
-  var x = 2;
-}
-console.log(x); // outputs 2
-
- -

This outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. In C or Java, the equivalent code would have outputted 1.

- -

Starting with ECMAScript2015, the let variable declaration is block scoped. See the {{jsxref("Statements/let", "let")}} reference page for more information.

- -

Conditional statements

- -

A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else and switch.

- -

if...else statement

- -

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false. An if statement looks as follows:

- -

if (condition) {
-   statement_1;
- } else {
-   statement_2;
- }

- -

Here the condition can be any expression that evaluates to true or false. See Boolean for an explanation of what evaluates to true and false. If condition evaluates to true, statement_1 is executed; otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.

- -

You may also compound the statements using else if to have multiple conditions tested in sequence, as follows:

- -
if (condition_1) {
-  statement_1;
-} else if (condition_2) {
-  statement_2;
-} else if (condition_n) {
-  statement_n;
-} else {
-  statement_last;
-}
-
- -

In the case of multiple conditions only the first logical condition which evaluates to true will be executed. To execute multiple statements, group them within a block statement ({ ... }) . In general, it's good practice to always use block statements, especially when nesting if statements:

- -
if (condition) {
-  statement_1_runs_if_condition_is_true;
-  statement_2_runs_if_condition_is_true;
-} else {
-  statement_3_runs_if_condition_is_false;
-  statement_4_runs_if_condition_is_false;
-}
-
- -
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
- -
if (x = y) {
-  /* statements here */
-}
-
- -

If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:

- -
if ((x = y)) {
-  /* statements here */
-}
-
- -

Falsy values

- -

The following values evaluate to false (also known as {{Glossary("Falsy")}} values):

- - - -

All other values, including all objects, evaluate to true when passed to a conditional statement.

- -

Do not confuse the primitive boolean values true and false with the true and false values of the {{jsxref("Boolean")}} object. For example:

- -
var b = new Boolean(false);
-if (b) // this condition evaluates to true
-if (b == true) // this condition evaluates to false
-
- -

Example

- -

In the following example, the function checkData returns true if the number of characters in a Text object is three; otherwise, it displays an alert and returns false.

- -
function checkData() {
-  if (document.form1.threeChar.value.length == 3) {
-    return true;
-  } else {
-    alert("Enter exactly three characters. " +
-    document.form1.threeChar.value + " is not valid.");
-    return false;
-  }
-}
-
- -

switch statement

- -

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch statement looks as follows:

- -
switch (expression) {
-  case label_1:
-    statements_1
-    [break;]
-  case label_2:
-    statements_2
-    [break;]
-    ...
-  default:
-    statements_def
-    [break;]
-}
-
- -

The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

- -

The optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

- -

Example

- -

In the following example, if fruittype evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program terminates switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

- -
switch (fruittype) {
-  case "Oranges":
-    console.log("Oranges are $0.59 a pound.");
-    break;
-  case "Apples":
-    console.log("Apples are $0.32 a pound.");
-    break;
-  case "Bananas":
-    console.log("Bananas are $0.48 a pound.");
-    break;
-  case "Cherries":
-    console.log("Cherries are $3.00 a pound.");
-    break;
-  case "Mangoes":
-    console.log("Mangoes are $0.56 a pound.");
-    break;
-  case "Papayas":
-    console.log("Mangoes and papayas are $2.79 a pound.");
-    break;
-  default:
-   console.log("Sorry, we are out of " + fruittype + ".");
-}
-console.log("Is there anything else you'd like?");
- -

Exception handling statements

- -

You can throw exceptions using the throw statement and handle them using the try...catch statements.

- - - -

Exception types

- -

Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is fairly common to throw numbers or strings as errors it is frequently more effective to use one of the exception types specifically created for this purpose:

- - - -

throw statement

- -

Use the throw statement to throw an exception. When you throw an exception, you specify the expression containing the value to be thrown:

- -
throw expression;
-
- -

You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:

- -
throw "Error2";   // String type
-throw 42;         // Number type
-throw true;       // Boolean type
-throw {toString: function() { return "I'm an object!"; } };
-
- -
Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object myUserException of type UserException and uses it in a throw statement.
- -
// Create an object type UserException
-function UserException(message) {
-  this.message = message;
-  this.name = "UserException";
-}
-
-// Make the exception convert to a pretty string when used as a string
-// (e.g. by the error console)
-UserException.prototype.toString = function() {
-  return this.name + ': "' + this.message + '"';
-}
-
-// Create an instance of the object type and throw it
-throw new UserException("Value too high");
- -

try...catch statement

- -

The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches it.

- -

The try...catch statement consists of a try block, which contains one or more statements, and a catch block, containing statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block. If no exception is thrown in the try block, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try...catch statement.

- -

The following example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (1-12), an exception is thrown with the value "InvalidMonthNo" and the statements in the catch block set the monthName variable to unknown.

- -
function getMonthName(mo) {
-  mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
-  var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul",
-                "Aug","Sep","Oct","Nov","Dec"];
-  if (months[mo]) {
-    return months[mo];
-  } else {
-    throw "InvalidMonthNo"; //throw keyword is used here
-  }
-}
-
-try { // statements to try
-  monthName = getMonthName(myMonth); // function could throw exception
-}
-catch (e) {
-  monthName = "unknown";
-  logMyErrors(e); // pass exception object to error handler -> your own function
-}
-
- -

The catch block

- -

You can use a catch block to handle all exceptions that may be generated in the try block.

- -
catch (catchID) {
-  statements
-}
-
- -

The catch block specifies an identifier (catchID in the preceding syntax) that holds the value specified by the throw statement; you can use this identifier to get information about the exception that was thrown. JavaScript creates this identifier when the catch block is entered; the identifier lasts only for the duration of the catch block; after the catch block finishes executing, the identifier is no longer available.

- -

For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.

- -
try {
-  throw "myException"; // generates an exception
-}
-catch (e) {
-  // statements to handle any exceptions
-  logMyErrors(e); // pass exception object to error handler
-}
-
- -

The finally block

- -

The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.

- -

You can use the finally block to make your script fail gracefully when an exception occurs; for example, you may need to release a resource that your script has tied up. The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the finally block closes the file before the script fails.

- -
openMyFile();
-try {
-  writeMyFile(theData); //This may throw a error
-} catch(e) {
-  handleError(e); // If we got a error we handle it
-} finally {
-  closeMyFile(); // always close the resource
-}
-
- -

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any return statements in the try and catch blocks:

- -
function f() {
-  try {
-    console.log(0);
-    throw "bogus";
-  } catch(e) {
-    console.log(1);
-    return true; // this return statement is suspended
-                 // until finally block has completed
-    console.log(2); // not reachable
-  } finally {
-    console.log(3);
-    return false; // overwrites the previous "return"
-    console.log(4); // not reachable
-  }
-  // "return false" is executed now
-  console.log(5); // not reachable
-}
-f(); // console 0, 1, 3; returns false
-
- -

Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch block:

- -
function f() {
-  try {
-    throw "bogus";
-  } catch(e) {
-    console.log('caught inner "bogus"');
-    throw e; // this throw statement is suspended until
-             // finally block has completed
-  } finally {
-    return false; // overwrites the previous "throw"
-  }
-  // "return false" is executed now
-}
-
-try {
-  f();
-} catch(e) {
-  // this is never reached because the throw inside
-  // the catch is overwritten
-  // by the return in finally
-  console.log('caught outer "bogus"');
-}
-
-// OUTPUT
-// caught inner "bogus"
- -

Nesting try...catch statements

- -

You can nest one or more try...catch statements. If an inner try...catch statement does not have a catch block, it needs to have a finally block and the enclosing try...catch statement's catch block is checked for a match. For more information, see nested try-blocks on the try...catch reference page.

- -

Utilizing Error objects

- -

Depending on the type of error, you may be able to use the 'name' and 'message' properties to get a more refined message. 'name' provides the general class of Error (e.g., 'DOMException' or 'Error'), while 'message' generally provides a more succinct message than one would get by converting the error object to a string.

- -

If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the Error constructor. For example:

- -
function doSomethingErrorProne () {
-  if (ourCodeMakesAMistake()) {
-    throw (new Error('The message'));
-  } else {
-    doSomethingToGetAJavascriptError();
-  }
-}
-....
-try {
-  doSomethingErrorProne();
-} catch (e) {
-  console.log(e.name); // logs 'Error'
-  console.log(e.message); // logs 'The message' or a JavaScript error message)
-}
- -

Promises

- -

Starting with ECMAScript2015, JavaScript gains support for {{jsxref("Promise")}} objects allowing you to control the flow of deferred and asynchronous operations.

- -

A Promise is in one of these states:

- - - -

- -

Loading an image with XHR

- -

A simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely. Here is the uncommented version, showing the Promise flow so that you can get an idea:

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

For more detailed information, see the {{jsxref("Promise")}} reference page.

- -
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
diff --git a/files/fa/web/javascript/guide/details_of_the_object_model/index.html b/files/fa/web/javascript/guide/details_of_the_object_model/index.html deleted file mode 100644 index 8562138526..0000000000 --- a/files/fa/web/javascript/guide/details_of_the_object_model/index.html +++ /dev/null @@ -1,719 +0,0 @@ ---- -title: Details of the object model -slug: Web/JavaScript/Guide/Details_of_the_Object_Model -translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model -original_slug: Web/JavaScript/راهنما/Details_of_the_Object_Model ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}
- -

JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This chapter attempts to clarify the situation.

- -

This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.

- -

Class-based vs. prototype-based languages

- -

Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.

- - - -

A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.

- -

تعریف یک کلاس

- -

In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the new operator in association with the constructor method to create class instances.

- -

JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the new operator with a constructor function to create a new object.

- -
-

Note that ECMAScript 2015 introduces a class declaration:

- -
-

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

-
-
- -

Subclasses and inheritance

- -

In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a subclass of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the Employee class includes only the name and dept properties, and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

- -

JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the EmployeeManager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, calling the Employee constructor and specifying the reports property. Finally, you assign a new object derived from Employee.prototype as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

- -

Adding and removing properties

- -

In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at run time. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at run time you can add or remove properties of any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.

- -

Summary of differences

- -

The following table gives a short summary of some of these differences. The rest of this chapter describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Comparison of class-based (Java) and prototype-based (JavaScript) object systems
CategoryClass-based (Java)Prototype-based (JavaScript)
Class vs. InstanceClass and instance are distinct entities.All objects can inherit from another object.
DefinitionDefine a class with a class definition; instantiate a class with constructor methods.Define and create a set of objects with constructor functions.
Creation of new objectCreate a single object with the new operator.Same.
Construction of object hierarchyConstruct an object hierarchy by using class definitions to define subclasses of existing classes.Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Inheritance modelInherit properties by following the class chain.Inherit properties by following the prototype chain.
Extension of propertiesClass definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time.Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.
- -

The employee example

- -

The remainder of this chapter uses the employee hierarchy shown in the following figure.

- -
-
-

A simple object hierarchy with the following objects:

- -

-
- -
-
    -
  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • -
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).
  • -
  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).
  • -
  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.
  • -
  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".
  • -
-
-
- -

Creating the hierarchy

- -

There are several ways to define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application.

- -

This section shows how to use very simple (and comparatively inflexible) definitions to demonstrate how to get the inheritance to work. In these definitions, you cannot specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time.

- -

In a real application, you would probably define constructors that allow you to provide property values at object creation time (see More flexible constructors for information). For now, these simple definitions demonstrate how the inheritance occurs.

- -

The following Java and JavaScript Employee definitions are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript (this is due to Java being a strongly typed language while JavaScript is a weakly typed language).

- -

JavaScript (using this may cause an error for the following examples)

- -
class Employee {
-  constructor() {
-    this.name = '';
-    this.dept = 'general';
-  }
-}
-
-
- -

JavaScript ** (use this instead)

- -
function Employee() {
-    this.name = '';
-    this.dept = 'general';
-}
-
-
- -

Java

- -
public class Employee {
-   public String name = "";
-   public String dept = "general";
-}
-
- -

The Manager and WorkerBee definitions show the difference in how to specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the prototype property of the constructor function, then override the prototype.constructor to the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.

- -

JavaScript

- -
function Manager() {
-  Employee.call(this);
-  this.reports = [];
-}
-Manager.prototype = Object.create(Employee.prototype);
-Manager.prototype.constructor = Manager;
-
-function WorkerBee() {
-  Employee.call(this);
-  this.projects = [];
-}
-WorkerBee.prototype = Object.create(Employee.prototype);
-WorkerBee.prototype.constructor = WorkerBee;
-
- -

Java

- -
public class Manager extends Employee {
-   public Employee[] reports =
-       new Employee[0];
-}
-
-
-
-public class WorkerBee extends Employee {
-   public String[] projects = new String[0];
-}
-
-
-
- -

The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the dept property with new values specific to these objects.

- -

JavaScript

- -
function SalesPerson() {
-   WorkerBee.call(this);
-   this.dept = 'sales';
-   this.quota = 100;
-}
-SalesPerson.prototype = Object.create(WorkerBee.prototype);
-SalesPerson.prototype.constructor = SalesPerson;
-
-function Engineer() {
-   WorkerBee.call(this);
-   this.dept = 'engineering';
-   this.machine = '';
-}
-Engineer.prototype = Object.create(WorkerBee.prototype)
-Engineer.prototype.constructor = Engineer;
-
- -

Java

- -
public class SalesPerson extends WorkerBee {
-   public String dept = "sales";
-   public double quota = 100.0;
-}
-
-
-public class Engineer extends WorkerBee {
-   public String dept = "engineering";
-   public String machine = "";
-}
-
-
- -

Using these definitions, you can create instances of these objects that get the default values for their properties. The next figure illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

- -
-

Note: The term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual instantiation of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.

-
- -

Creating objects with simple definitions

- -
-

Object hierarchy

- -

The following hierarchy is created using the code on the right side.

- -

- -

Individual objects = Jim, Sally, Mark, Fred, Jane, etc.
- "Instances" created from constructor

- -
var jim = new Employee;
-// Parentheses can be omitted if the
-// constructor takes no arguments.
-// jim.name is ''
-// jim.dept is 'general'
-
-var sally = new Manager;
-// sally.name is ''
-// sally.dept is 'general'
-// sally.reports is []
-
-var mark = new WorkerBee;
-// mark.name is ''
-// mark.dept is 'general'
-// mark.projects is []
-
-var fred = new SalesPerson;
-// fred.name is ''
-// fred.dept is 'sales'
-// fred.projects is []
-// fred.quota is 100
-
-var jane = new Engineer;
-// jane.name is ''
-// jane.dept is 'engineering'
-// jane.projects is []
-// jane.machine is ''
-
-
- -

Object properties

- -

This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at run time.

- -

Inheriting properties

- -

Suppose you create the mark object as a WorkerBee with the following statement:

- -
var mark = new WorkerBee;
-
- -

When JavaScript sees the new operator, it creates a new generic object and implicitly sets the value of the internal property [[Prototype]] to the value of WorkerBee.prototype and passes this new object as the value of the this keyword to the WorkerBee constructor function. The internal [[Prototype]] property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable mark to that object.

- -

This process does not explicitly put values in the mark object (local values) for the properties that mark inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value is not there locally, JavaScript checks the prototype chain (using the internal [[Prototype]] property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object does not have the property. In this way, the mark object has the following properties and values:

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

The mark object is assigned local values for the name and dept properties by the Employee constructor. It is assigned a local value for the projects property by the WorkerBee constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in Property inheritance revisited.

- -

Because these constructors do not let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as follows:

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

Adding properties

- -

In JavaScript, you can add properties to any object at run time. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you assign a value to the object, as follows:

- -
mark.bonus = 3000;
-
- -

Now, the mark object has a bonus property, but no other WorkerBee has this property.

- -

If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

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

As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". The following figure shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

- -


- Adding properties

- -

More flexible constructors

- -

The constructor functions shown so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. The following figure shows one way to do this.

- -


- Specifying properties in a constructor, take 1

- -

The following pairs of examples show the Java and JavaScript definitions for these objects.

- -
function Employee(name, dept) {
-  this.name = name || '';
-  this.dept = dept || 'general';
-}
-
- -
public class Employee {
-   public String name;
-   public String dept;
-   public Employee () {
-      this("", "general");
-   }
-   public Employee (String name) {
-      this(name, "general");
-   }
-   public Employee (String name, String dept) {
-      this.name = name;
-      this.dept = dept;
-   }
-}
-
- -
function WorkerBee(projs) {
-  this.projects = projs || [];
-}
-WorkerBee.prototype = new Employee;
-
- -
public class WorkerBee extends Employee {
-   public String[] projects;
-   public WorkerBee () {
-      this(new String[0]);
-   }
-   public WorkerBee (String[] projs) {
-      projects = projs;
-   }
-}
-
- -
-function Engineer(mach) {
-  this.dept = 'engineering';
-  this.machine = mach || '';
-}
-Engineer.prototype = new WorkerBee;
-
- -
public class Engineer extends WorkerBee {
-   public String machine;
-   public Engineer () {
-      dept = "engineering";
-      machine = "";
-   }
-   public Engineer (String mach) {
-      dept = "engineering";
-      machine = mach;
-   }
-}
-
- -

These JavaScript definitions use a special idiom for setting default values:

- -
this.name = name || '';
-
- -

The JavaScript logical OR operator (||) evaluates its first argument. If that argument converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.

- -
-

Note: This may not work as expected if the constructor function is called with arguments which convert to false (like 0 (zero) and empty string (""). In this case the default value will be chosen.

-
- -

With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. You can use the following statement to create a new Engineer:

- -
var jane = new Engineer('belau');
-
- -

Jane's properties are now:

- -
jane.name == '';
-jane.dept == 'engineering';
-jane.projects == [];
-jane.machine == 'belau';
-
- -

Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

- -

So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. The following figure shows these new definitions.

- -


- Specifying properties in a constructor, take 2

- -

Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

- -
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-
- -

Suppose you create a new Engineer object as follows:

- -
var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau');
-
- -

JavaScript follows these steps:

- -
    -
  1. The new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
  2. -
  3. The new operator passes the new object to the Engineer constructor as the value of the this keyword.
  4. -
  5. The constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object. The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
  6. -
  7. The constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property, and this value overrides the value inherited from Employee.
  8. -
  9. Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in Step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and "engineering" arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
  10. -
  11. Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
  12. -
  13. Upon return from the constructor, JavaScript assigns the new object to the jane variable.
  14. -
- -

You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you have set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have the following statements:

- -
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau');
-Employee.prototype.specialty = 'none';
-
- -

The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

- -
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-Engineer.prototype = new WorkerBee;
-var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau');
-Employee.prototype.specialty = 'none';
-
- -

Now the value of the jane object's specialty property is "none".

- -

Another way of inheriting is by using the call() / apply() methods. Below are equivalent:

- -
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-
- -
function Engineer(name, projs, mach) {
-  WorkerBee.call(this, name, 'engineering', projs);
-  this.machine = mach || '';
-}
-
- -

Using the javascript call() method makes a cleaner implementation because the base is not needed anymore.

- -

Property inheritance revisited

- -

The preceding sections described how JavaScript constructors and prototypes provide hierarchies and inheritance. This section discusses some subtleties that were not necessarily apparent in the earlier discussions.

- -

Local versus inherited values

- -

When you access an object property, JavaScript performs these steps, as described earlier in this chapter:

- -
    -
  1. Check to see if the value exists locally. If it does, return that value.
  2. -
  3. If there is not a local value, check the prototype chain (using the __proto__ property).
  4. -
  5. If an object in the prototype chain has a value for the specified property, return that value.
  6. -
  7. If no such property is found, the object does not have the property.
  8. -
- -

The outcome of these steps depends on how you define things along the way. The original example had these definitions:

- -
function Employee() {
-  this.name = '';
-  this.dept = 'general';
-}
-
-function WorkerBee() {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
- -

With these definitions, suppose you create amy as an instance of WorkerBee with the following statement:

- -
var amy = new WorkerBee;
-
- -

The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so derive from the amy object's __proto__ property. Thus, amy has these property values:

- -
amy.name == '';
-amy.dept == 'general';
-amy.projects == [];
-
- -

Now suppose you change the value of the name property in the prototype associated with Employee:

- -
Employee.prototype.name = 'Unknown';
-
- -

At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

- -

When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look further up the chain to Employee.prototype.

- -

If you want to change the value of an object property at run time and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the preceding code to the following:

- -
function Employee() {
-  this.dept = 'general';    // Note that this.name (a local variable) does not appear here
-}
-Employee.prototype.name = '';    // A single copy
-
-function WorkerBee() {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
-var amy = new WorkerBee;
-
-Employee.prototype.name = 'Unknown';
-
- -

In this case, the name property of amy becomes "Unknown".

- -

As these examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself.

- -

Determining instance relationships

- -

Property lookup in JavaScript looks within an object's own properties and, if the property name is not found, it looks within the special object property __proto__. This continues recursively; the process is called "lookup in the prototype chain".

- -

The special property __proto__ is set when an object is constructed; it is set to the value of the constructor's prototype property. So the expression new Foo() creates an object with __proto__ == Foo.prototype. Consequently, changes to the properties of Foo.prototype alters the property lookup for all objects that were created by new Foo().

- -

Every object has a __proto__ object property (except Object); every function has a prototype object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to a function's prototype object. JavaScript provides a shortcut: the instanceof operator tests an object against a function and returns true if the object inherits from the function prototype. For example,

- -
var f = new Foo();
-var isTrue = (f instanceof Foo);
- -

For a more detailed example, suppose you have the same set of definitions shown in Inheriting properties. Create an Engineer object as follows:

- -
var chris = new Engineer('Pigman, Chris', ['jsd'], 'fiji');
-
- -

With this object, the following statements are all true:

- -
chris.__proto__ == Engineer.prototype;
-chris.__proto__.__proto__ == WorkerBee.prototype;
-chris.__proto__.__proto__.__proto__ == Employee.prototype;
-chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
-chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;
-
- -

Given this, you could write an instanceOf function as follows:

- -
function instanceOf(object, constructor) {
-   object = object.__proto__;
-   while (object != null) {
-      if (object == constructor.prototype)
-         return true;
-      if (typeof object == 'xml') {
-        return constructor.prototype == XML.prototype;
-      }
-      object = object.__proto__;
-   }
-   return false;
-}
-
- -
Note: The implementation above checks the type of the object against "xml" in order to work around a quirk of how XML objects are represented in recent versions of JavaScript. See bug 634150 if you want the nitty-gritty details.
- -

Using the instanceOf function defined above, these expressions are true:

- -
instanceOf(chris, Engineer)
-instanceOf(chris, WorkerBee)
-instanceOf(chris, Employee)
-instanceOf(chris, Object)
-
- -

But the following expression is false:

- -
instanceOf(chris, SalesPerson)
-
- -

Global information in constructors

- -

When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use the following definition for Employee:

- -
var idCounter = 1;
-
-function Employee(name, dept) {
-   this.name = name || '';
-   this.dept = dept || 'general';
-   this.id = idCounter++;
-}
-
- -

With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, victoria.id is 1 and harry.id is 2:

- -
var victoria = new Employee('Pigbert, Victoria', 'pubs');
-var harry = new Employee('Tschopik, Harry', 'sales');
-
- -

At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy shown in this chapter, the Employee constructor is called every time you set up a prototype. Suppose you have the following code:

- -
var idCounter = 1;
-
-function Employee(name, dept) {
-   this.name = name || '';
-   this.dept = dept || 'general';
-   this.id = idCounter++;
-}
-
-function Manager(name, dept, reports) {...}
-Manager.prototype = new Employee;
-
-function WorkerBee(name, dept, projs) {...}
-WorkerBee.prototype = new Employee;
-
-function Engineer(name, projs, mach) {...}
-Engineer.prototype = new WorkerBee;
-
-function SalesPerson(name, projs, quota) {...}
-SalesPerson.prototype = new WorkerBee;
-
-var mac = new Engineer('Wood, Mac');
-
- -

Further assume that the definitions omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

- -

Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using the following constructor:

- -
function Employee(name, dept) {
-   this.name = name || '';
-   this.dept = dept || 'general';
-   if (name)
-      this.id = idCounter++;
-}
-
- -

When you create an instance of Employee to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an Employee to get an assigned id, you must specify a name for the employee. In this example, mac.id would be 1.

- -

Alternatively, you can create a copy of Employee's prototype object to assign to WorkerBee:

- -
WorkerBee.prototype = Object.create(Employee.prototype);
-// instead of WorkerBee.prototype = new Employee
-
- -

No multiple inheritance

- -

Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.

- -

Inheritance of property values occurs at run time by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.

- -

In JavaScript, you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:

- -
function Hobbyist(hobby) {
-   this.hobby = hobby || 'scuba';
-}
-
-function Engineer(name, projs, mach, hobby) {
-   this.base1 = WorkerBee;
-   this.base1(name, 'engineering', projs);
-   this.base2 = Hobbyist;
-   this.base2(hobby);
-   this.machine = mach || '';
-}
-Engineer.prototype = new WorkerBee;
-
-var dennis = new Engineer('Doe, Dennis', ['collabra'], 'hugo');
-
- -

Further assume that the definition of WorkerBee is as used earlier in this chapter. In this case, the dennis object has these properties:

- -
dennis.name == 'Doe, Dennis';
-dennis.dept == 'engineering';
-dennis.projects == ['collabra'];
-dennis.machine == 'hugo';
-dennis.hobby == 'scuba';
-
- -

So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

- -
Hobbyist.prototype.equipment = ['mask', 'fins', 'regulator', 'bcd'];
-
- -

The dennis object does not inherit this new property.

- -
{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}
diff --git a/files/fa/web/javascript/guide/functions/index.html b/files/fa/web/javascript/guide/functions/index.html deleted file mode 100644 index 5e4f1a8c63..0000000000 --- a/files/fa/web/javascript/guide/functions/index.html +++ /dev/null @@ -1,649 +0,0 @@ ---- -title: Functions -slug: Web/JavaScript/Guide/Functions -translation_of: Web/JavaScript/Guide/Functions -original_slug: Web/JavaScript/راهنما/Functions ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}
- -

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.

- -

See also the exhaustive reference chapter about JavaScript functions to get to know the details.

- -

Defining functions

- -

Function declarations

- -

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

- - - -

For example, the following code defines a simple function named square:

- -
function square(number) {
-  return number * number;
-}
-
- -

The function square takes one parameter, called number. The function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. The return statement specifies the value returned by the function.

- -
return number * number;
-
- -

Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

- -

If you pass an object (i.e. a non-primitive value, such as {{jsxref("Array")}} or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example:

- -
function myFunc(theObject) {
-  theObject.make = 'Toyota';
-}
-
-var mycar = {make: 'Honda', model: 'Accord', year: 1998};
-var x, y;
-
-x = mycar.make; // x gets the value "Honda"
-
-myFunc(mycar);
-y = mycar.make; // y gets the value "Toyota"
-                // (the make property was changed by the function)
-
- -

Function expressions

- -

While the function declaration above is syntactically a statement, functions can also be created by a function expression. Such a function can be anonymous; it does not have to have a name. For example, the function square could have been defined as:

- -
var square = function(number) { return number * number; };
-var x = square(4); // x gets the value 16
- -

However, a name can be provided with a function expression and can be used inside the function to refer to itself, or in a debugger to identify the function in stack traces:

- -
var factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); };
-
-console.log(factorial(3));
-
- -

Function expressions are convenient when passing a function as an argument to another function. The following example shows a map function being defined and then called with an expression function as its first parameter:

- -
function map(f, a) {
-  var result = [], // Create a new Array
-      i;
-  for (i = 0; i != a.length; i++)
-    result[i] = f(a[i]);
-  return result;
-}
-
- -

The following code:

- -
var numbers = [0,1, 2, 5,10];
-var cube= numbers.map(function(x) {
-   return x * x * x;
-});
-console.log(cube);
- -

returns [0, 1, 8, 125, 1000].

- -

In JavaScript, a function can be defined based on a condition. For example, the following function definition defines myFunc only if num equals 0:

- -
var myFunc;
-if (num === 0) {
-  myFunc = function(theObject) {
-    theObject.make = 'Toyota';
-  }
-}
- -

In addition to defining functions as described here, you can also use the {{jsxref("Function")}} constructor to create functions from a string at runtime, much like {{jsxref("eval", "eval()")}}.

- -

A method is a function that is a property of an object. Read more about objects and methods in Working with objects.

- -

Calling functions

- -

Defining a function does not execute it. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows:

- -
square(5);
-
- -

The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25.

- -

Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code), as in this example:

- -
console.log(square(5));
-/* ... */
-function square(n) { return n * n; }
-
- -

The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level.

- -
-

Note: This works only when defining the function using the above syntax (i.e. function funcName(){}). The code below will not work. That means, function hoisting only works with function declaration and not with function expression.

-
- -
console.log(square); // square is hoisted with an initial value undefined.
-console.log(square(5)); // TypeError: square is not a function
-var square = function(n) {
-  return n * n;
-}
-
- -

The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The show_props() function (defined in Working with objects) is an example of a function that takes an object as an argument.

- -

A function can call itself. For example, here is a function that computes factorials recursively:

- -
function factorial(n) {
-  if ((n === 0) || (n === 1))
-    return 1;
-  else
-    return (n * factorial(n - 1));
-}
-
- -

You could then compute the factorials of one through five as follows:

- -
var a, b, c, d, e;
-a = factorial(1); // a gets the value 1
-b = factorial(2); // b gets the value 2
-c = factorial(3); // c gets the value 6
-d = factorial(4); // d gets the value 24
-e = factorial(5); // e gets the value 120
-
- -

There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that functions are, themselves, objects, and these objects in turn have methods (see the {{jsxref("Function")}} object). One of these, the {{jsxref("Function.apply", "apply()")}} method, can be used to achieve this goal.

- -

Function scope

- -

Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function and any other variable to which the parent function has access.

- -
// The following variables are defined in the global scope
-var num1 = 20,
-    num2 = 3,
-    name = 'Chamahk';
-
-// This function is defined in the global scope
-function multiply() {
-  return num1 * num2;
-}
-
-multiply(); // Returns 60
-
-// A nested function example
-function getScore() {
-  var num1 = 2,
-      num2 = 3;
-
-  function add() {
-    return name + ' scored ' + (num1 + num2);
-  }
-
-  return add();
-}
-
-getScore(); // Returns "Chamahk scored 5"
-
- -

Scope and the function stack

- -

Recursion

- -

A function can refer to and call itself. There are three ways for a function to refer to itself:

- -
    -
  1. the function's name
  2. -
  3. arguments.callee
  4. -
  5. an in-scope variable that refers to the function
  6. -
- -

For example, consider the following function definition:

- -
var foo = function bar() {
-   // statements go here
-};
-
- -

Within the function body, the following are all equivalent:

- -
    -
  1. bar()
  2. -
  3. arguments.callee()
  4. -
  5. foo()
  6. -
- -

A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, the following loop:

- -
var x = 0;
-while (x < 10) { // "x < 10" is the loop condition
-   // do stuff
-   x++;
-}
-
- -

can be converted into a recursive function and a call to that function:

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
-    return;
-  // do stuff
-  loop(x + 1); // the recursive call
-}
-loop(0);
-
- -

However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the DOM) is more easily done using recursion:

- -
function walkTree(node) {
-  if (node == null) //
-    return;
-  // do something with node
-  for (var i = 0; i < node.childNodes.length; i++) {
-    walkTree(node.childNodes[i]);
-  }
-}
-
- -

Compared to the function loop, each recursive call itself makes many recursive calls here.

- -

It is possible to convert any recursive algorithm to a non-recursive one, but often the logic is much more complex and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack.

- -

The stack-like behavior can be seen in the following example:

- -
function foo(i) {
-  if (i < 0)
-    return;
-  console.log('begin: ' + i);
-  foo(i - 1);
-  console.log('end: ' + i);
-}
-foo(3);
-
-// Output:
-
-// begin: 3
-// begin: 2
-// begin: 1
-// begin: 0
-// end: 0
-// end: 1
-// end: 2
-// end: 3
- -

Nested functions and closures

- -

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure. A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

- -

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

- -

To summarize:

- - - - - -

The following example shows nested functions:

- -
function addSquares(a, b) {
-  function square(x) {
-    return x * x;
-  }
-  return square(a) + square(b);
-}
-a = addSquares(2, 3); // returns 13
-b = addSquares(3, 4); // returns 25
-c = addSquares(4, 5); // returns 41
-
- -

Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

- -
function outside(x) {
-  function inside(y) {
-    return x + y;
-  }
-  return inside;
-}
-fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
-result = fn_inside(5); // returns 8
-
-result1 = outside(3)(5); // returns 8
-
- -

Preservation of variables

- -

Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible.

- -

This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.

- -

Multiply-nested functions

- -

Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (Why it is called "chaining" will be explained later.)

- -

Consider the following example:

- -
function A(x) {
-  function B(y) {
-    function C(z) {
-      console.log(x + y + z);
-    }
-    C(3);
-  }
-  B(2);
-}
-A(1); // logs 6 (1 + 2 + 3)
-
- -

In this example, C accesses B's y and A's x. This can be done because:

- -
    -
  1. B forms a closure including A, i.e. B can access A's arguments and variables.
  2. -
  3. C forms a closure including B.
  4. -
  5. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A in that order.
  6. -
- -

The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.

- -

Name conflicts

- -

When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:

- -
function outside() {
-  var x = 5;
-  function inside(x) {
-    return x * 2;
-  }
-  return inside;
-}
-
-outside()(10); // returns 20 instead of 10
-
- -

The name conflict happens at the statement return x and is between inside's parameter x and outside's variable x. The scope chain here is {inside, outside, global object}. Therefore inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x).

- -

Closures

- -

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of security for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the inner function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

- -
var pet = function(name) {   // The outer function defines a variable called "name"
-  var getName = function() {
-    return name;             // The inner function has access to the "name" variable of the outer function
-  }
-  return getName;            // Return the inner function, thereby exposing it to outer scopes
-}
-myPet = pet('Vivie');
-
-myPet();                     // Returns "Vivie"
-
- -

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

- -
var createPet = function(name) {
-  var sex;
-
-  return {
-    setName: function(newName) {
-      name = newName;
-    },
-
-    getName: function() {
-      return name;
-    },
-
-    getSex: function() {
-      return sex;
-    },
-
-    setSex: function(newSex) {
-      if(typeof newSex === 'string' && (newSex.toLowerCase() === 'male' || newSex.toLowerCase() === 'female')) {
-        sex = newSex;
-      }
-    }
-  }
-}
-
-var pet = createPet('Vivie');
-pet.getName();                  // Vivie
-
-pet.setName('Oliver');
-pet.setSex('male');
-pet.getSex();                   // male
-pet.getName();                  // Oliver
-
- -

In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent", yet secure, data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

- -
var getCode = (function() {
-  var secureCode = '0]Eal(eh&2';    // A code we do not want outsiders to be able to modify...
-
-  return function() {
-    return secureCode;
-  };
-}());
-
-getCode();    // Returns the secureCode
-
- -

There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again.

- -
var createPet = function(name) {  // Outer function defines a variable called "name"
-  return {
-    setName: function(name) {    // Enclosed function also defines a variable called "name"
-      name = name;               // ??? How do we access the "name" defined by the outer function ???
-    }
-  }
-}
-
- -

Using the arguments object

- -

The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

- -
arguments[i]
-
- -

where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

- -

Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

- -

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

- -
function myConcat(separator) {
-   var result = ''; // initialize list
-   var i;
-   // iterate through arguments
-   for (i = 1; i < arguments.length; i++) {
-      result += arguments[i] + separator;
-   }
-   return result;
-}
-
- -

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

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

Note: The arguments variable is "array-like", but not an array. It is array-like in that it has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.

-
- -

See the {{jsxref("Function")}} object in the JavaScript reference for more information.

- -

Function parameters

- -

Starting with ECMAScript 2015, there are two new kinds of parameters: default parameters and rest parameters.

- -

Default parameters

- -

In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is where default parameters can help.

- -

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined. If in the following example, no value is provided for b in the call, its value would be undefined  when evaluating a*b and the call to multiply would have returned NaN. However, this is caught with the second line in this example:

- -
function multiply(a, b) {
-  b = typeof b !== 'undefined' ?  b : 1;
-
-  return a * b;
-}
-
-multiply(5); // 5
-
- -

With default parameters, the check in the function body is no longer necessary. Now, you can simply put 1 as the default value for b in the function head:

- -
function multiply(a, b = 1) {
-  return a * b;
-}
-
-multiply(5); // 5
- -

For more details, see default parameters in the reference.

- -

Rest parameters

- -

The rest parameter syntax allows us to represent an indefinite number of arguments as an array. In the example, we use the rest parameters to collect arguments from the second one to the end. We then multiply them by the first one. This example is using an arrow function, which is introduced in the next section.

- -
function multiply(multiplier, ...theArgs) {
-  return theArgs.map(x => multiplier * x);
-}
-
-var arr = multiply(2, 1, 2, 3);
-console.log(arr); // [2, 4, 6]
- -

Arrow functions

- -

An arrow function expression (previously, and now incorrectly known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous. See also this hacks.mozilla.org blog post: "ES6 In Depth: Arrow functions".

- -

Two factors influenced the introduction of arrow functions: shorter functions and lexical this.

- -

Shorter functions

- -

In some functional patterns, shorter functions are welcome. Compare:

- -
var a = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-var a2 = a.map(function(s) { return s.length; });
-
-console.log(a2); // logs [8, 6, 7, 9]
-
-var a3 = a.map(s => s.length);
-
-console.log(a3); // logs [8, 6, 7, 9]
-
- -

Lexical this

- -

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

- -
function Person() {
-  // The Person() constructor defines `this` as itself.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // In nonstrict mode, the growUp() function defines `this`
-    // as the global object, which is different from the `this`
-    // defined by the Person() constructor.
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

- -
function Person() {
-  var self = this; // Some choose `that` instead of `self`.
-                   // Choose one and be consistent.
-  self.age = 0;
-
-  setInterval(function growUp() {
-    // The callback refers to the `self` variable of which
-    // the value is the expected object.
-    self.age++;
-  }, 1000);
-}
- -

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function.

- -

Arrow functions capture the this value of the enclosing context, so the following code works as expected.

- -
function Person() {
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| properly refers to the person object
-  }, 1000);
-}
-
-var p = new Person();
- -

Predefined functions

- -

JavaScript has several top-level, built-in functions:

- -
-
{{jsxref("Global_Objects/eval", "eval()")}}
-
-

The eval() method evaluates JavaScript code represented as a string.

-
-
{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
-
-

The uneval() method creates a string representation of the source code of an {{jsxref("Object")}}.

-
-
{{jsxref("Global_Objects/isFinite", "isFinite()")}}
-
-

The global isFinite() function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.

-
-
{{jsxref("Global_Objects/isNaN", "isNaN()")}}
-
-

The isNaN() function determines whether a value is {{jsxref("Global_Objects/NaN", "NaN")}} or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use {{jsxref("Number.isNaN()")}}, as defined in ECMAScript 2015, or you can use typeof to determine if the value is Not-A-Number.

-
-
{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
-
-

The parseFloat() function parses a string argument and returns a floating point number.

-
-
{{jsxref("Global_Objects/parseInt", "parseInt()")}}
-
-

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

-
-
{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
-
-

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or by a similar routine.

-
-
{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
-
-

The decodeURIComponent() method decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} or by a similar routine.

-
-
{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
-
-

The encodeURI() method encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

-
-
{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
-
-

The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

-
-
{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
-
-

The deprecated escape() method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} instead.

-
-
{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
-
-

The deprecated unescape() method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like {{jsxref("Global_Objects/escape", "escape")}}. Because unescape() is deprecated, use {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} instead.

-
-
- -

{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}

diff --git a/files/fa/web/javascript/guide/grammar_and_types/index.html b/files/fa/web/javascript/guide/grammar_and_types/index.html deleted file mode 100644 index c42b672d21..0000000000 --- a/files/fa/web/javascript/guide/grammar_and_types/index.html +++ /dev/null @@ -1,674 +0,0 @@ ---- -title: گرامر و انواع -slug: Web/JavaScript/Guide/Grammar_and_types -translation_of: Web/JavaScript/Guide/Grammar_and_types -original_slug: Web/JavaScript/راهنما/Grammar_and_types ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
- -

این فصل در مورد گرامر اولیه جاوااسکریپت، اعلان‌های متغیر، انواع داده و لیترال‌ها است.

- -

مقدمه

- -

جاوااسکریپت قسمت زیادی از نحو خود را از جاوا اقتباس کرده و همچنین از زبانهای پرل، پایتون و Awk  تاثیر گرفته است.

- -

جاوااسکریپت حساس به کوچکی و بزرگی حروف (case-sensetive) است و از مجموعه کاراکترهای یونیکد (Unicode) استفاده می‌کند.

- -

In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by a semicolon (;). Spaces, tabs and newline characters are called whitespace. The source text of JavaScript scripts gets scanned from left to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or whitespace. ECMAScript also defines certain keywords and literals and has rules for automatic insertion of semicolons (ASI) to end statements. However, it is recommended to always add semicolons to end your statements; it will avoid side effects. For more information, see the detailed reference about JavaScript's lexical grammar.

- -

توضیح (comment)

- -

نحو (syntax) یک «توضیح» مشابه با زبان C++ و تعداد زیادی از زبانهای دیگر است.
- مثال اول: توضیح تک‌خطی
- مثال دوم:  توضیح چندخطی (بلوک)
- مثال سوم: اگرچه، برخلاف c++  نمی‌توان توضیح تو در تو ساخت. احتمالا خطای نحوی خواهد بود.

- -
// a one line comment
-
-/* this is a longer,
-   multi-line comment
- */
-
-/* You can't, however, /* nest comments */ SyntaxError */
- -

اعلان‌ها (Declarations)

- -

سه نوع اعلان در جاوااسکریپت وجود دارد.

- -
-
{{jsxref("Statements/var", "var")}}
-
یک متغیر را اعلان می‌کند. مقداردهی اولیه اختیاری است.
-
{{jsxref("Statements/let", "let")}}
-
یک متغیر محلی را با قلمرو بلوک اعلان می‌کند. مقداردهی اولیه اختیاری است.
-
{{jsxref("Statements/const", "const")}}
-
یک ثابت «فقط خواندنی» را اعلان می‌کند.
-
- -

متغیرها

- -

You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.

- -

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

- -

You can use most of ISO 8859-1 or Unicode letters such as å and ü in identifiers (for more details see this blog post). You can also use the Unicode escape sequences as characters in identifiers.

- -

نام‌های روبرو مثال‌هایی معتبر برای نامگذاری هستند: Number_hits, temp99_name

- -

اعلان متغیرها

- -

شما به سه روش می‌توانید یک متغیر را اعلان کنید:

- - - -

ارزیابی متغیرها

- -

A variable declared using the var or let statement with no initial value specified has the value {{jsxref("undefined")}}.

- -

An attempt to access an undeclared variable will result in a {{jsxref("ReferenceError")}} exception being thrown:

- -
var a;
-console.log("The value of a is " + a); // The value of a is undefined
-
-var b;
-console.log("The value of b is " + b); // The value of b is undefined
-
-console.log("The value of c is " + c); // Uncaught ReferenceError: c is not defined
-
-let x;
-console.log("The value of x is " + x); // The value of x is undefined
-
-console.log("The value of y is " + y); // Uncaught ReferenceError: y is not defined
-let y; 
- -

شما می‌توانید از undefined برای مشخص کردن اینکه آیا یک متغیر دارای مقدار است استفاده کنید. در کد زیر به متغیر input مقداری انتساب داده نشده است و عبارت منطقی if برابر با true ارزیابی می‌شود.

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

رفتار مقدار undefined در ارزیابی عبارات منطقی مانند false است. برای مثال، در کد زیر تابع  myFunction  اجرا خواهد شد چون المان myArray تعریف‌نشده است:

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

در یک عبارت عددی مقدار undefined به  NaN تبدیل می‌شود.

- -
var a;
-a + 2;  // Evaluates to NaN
- -

وقتی یک متغیر {{jsxref("null")}} را ارزیابی می‌کنید، در یک عبارت عددی دارای مقدارصفر و در یک عبارت منطقی دارای مقدار false خواهد بود. برای مثال:

- -
var n = null;
-console.log(n * 32); // Will log 0 to the console
-
- -

قلمرو متغیر (Variable Scope)

- -

When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.

- -

JavaScript before ECMAScript 2015 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

- -
if (true) {
-  var x = 5;
-}
-console.log(x);  // x is 5
-
- -

This behavior changes, when using the let declaration introduced in ECMAScript 2015.

- -
if (true) {
-  let y = 5;
-}
-console.log(y);  // ReferenceError: y is not defined
-
- -

Variable hoisting

- -

Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that are hoisted will return a value of undefined. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.

- -
/**
- * Example 1
- */
-console.log(x === undefined); // true
-var x = 3;
-
-/**
- * Example 2
- */
-// will return a value of undefined
-var myvar = "my value";
-
-(function() {
-  console.log(myvar); // undefined
-  var myvar = "local value";
-})();
-
- -

The above examples will be interpreted the same as:

- -
/**
- * Example 1
- */
-var x;
-console.log(x === undefined); // true
-x = 3;
-
-/**
- * Example 2
- */
-var myvar = "my value";
-
-(function() {
-  var myvar;
-  console.log(myvar); // undefined
-  myvar = "local value";
-})();
-
- -

Because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.

- -

In ECMAScript 2015, let (const) will not hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a {{jsxref("ReferenceError")}}. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

- -
console.log(x); // ReferenceError
-let x = 3;
- -

Function hoisting

- -

For functions, only function declaration gets hoisted to the top and not the function expression.

- -
/* Function declaration */
-
-foo(); // "bar"
-
-function foo() {
-  console.log("bar");
-}
-
-
-/* Function expression */
-
-baz(); // TypeError: baz is not a function
-
-var baz = function() {
-  console.log("bar2");
-};
-
- -

Global variables

- -

Global variables are in fact properties of the global object. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the window.variable syntax.

- -

Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber.

- -

Constants

- -

You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.

- -
const PI = 3.14;
-
- -

A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.

- -

The scope rules for constants are the same as those for let block scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.

- -

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

- -
// THIS WILL CAUSE AN ERROR
-function f() {};
-const f = 5;
-
-// THIS WILL CAUSE AN ERROR ALSO
-function f() {
-  const g = 5;
-  var g;
-
-  //statements
-}
-
- -

However, the properties of objects assigned to constants are not protected, so the following statement is executed without problems.

- -
const MY_OBJECT = {"key": "value"};
-MY_OBJECT.key = "otherValue";
- -

Data structures and types

- -

Data types

- -

The latest ECMAScript standard defines seven data types:

- - - -

Although these data types are a relatively small amount, they enable you to perform useful functions with your applications. {{jsxref("Object", "Objects")}} and {{jsxref("Function", "functions")}} are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.

- -

Data type conversion

- -

JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:

- -
var answer = 42;
-
- -

And later, you could assign the same variable a string value, for example:

- -
answer = "Thanks for all the fish...";
-
- -

Because JavaScript is dynamically typed, this assignment does not cause an error message.

- -

In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:

- -
x = "The answer is " + 42 // "The answer is 42"
-y = 42 + " is the answer" // "42 is the answer"
-
- -

In statements involving other operators, JavaScript does not convert numeric values to strings. For example:

- -
"37" - 7 // 30
-"37" + 7 // "377"
-
- -

Converting strings to numbers

- -

In the case that a value representing a number is in memory as a string, there are methods for conversion.

- - - -

parseInt will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for parseInt is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.

- -

An alternative method of retrieving a number from a string is with the + (unary plus) operator:

- -
"1.1" + "1.1" = "1.11.1"
-(+"1.1") + (+"1.1") = 2.2
-// Note: the parentheses are added for clarity, not required.
- -

Literals

- -

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

- - - -

Array literals

- -

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

- -

The following example creates the coffees array with three elements and a length of three:

- -
var coffees = ["French Roast", "Colombian", "Kona"];
-
- -
-

Note : An array literal is a type of object initializer. See Using Object Initializers.

-
- -

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

- -

Array literals are also Array objects. See {{jsxref("Array")}} and Indexed collections for details on Array objects.

- -

Extra commas in array literals

- -

You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with undefined for the unspecified elements. The following example creates the fish array:

- -
var fish = ["Lion", , "Angel"];
-
- -

This array has two elements with values and one empty element (fish[0] is "Lion", fish[1] is undefined, and fish[2] is "Angel").

- -

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element.

- -
-

Note : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

-
- -
var myList = ['home', , 'school', ];
-
- -

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

- -
var myList = [ , 'home', , 'school'];
-
- -

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

- -
var myList = ['home', , 'school', , ];
-
- -

Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as undefined will increase your code's clarity and maintainability.

- -

Boolean literals

- -

The Boolean type has two literal values: true and false.

- -

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See {{jsxref("Boolean")}} for more information.

- -

Integers

- -

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

- - - -

Some examples of integer literals are:

- -
0, 117 and -345 (decimal, base 10)
-015, 0001 and -0o77 (octal, base 8)
-0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
-0b11, 0b0011 and -0b11 (binary, base 2)
-
- -

For more information, see Numeric literals in the Lexical grammar reference.

- -

Floating-point literals

- -

A floating-point literal can have the following parts:

- - - -

The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").

- -

More succinctly, the syntax is:

- -
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
-
- -

For example:

- -
3.1415926
--.123456789
--3.1E+12
-.1e-23
-
- -

Object literals

- -

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

- -

The following is an example of an object literal. The first element of the car object defines a property, myCar, and assigns to it a new string, "Saturn"; the second element, the getCar property, is immediately assigned the result of invoking the function (carTypes("Honda")); the third element, the special property, uses an existing variable (sales).

- -
var sales = "Toyota";
-
-function carTypes(name) {
-  if (name === "Honda") {
-    return name;
-  } else {
-    return "Sorry, we don't sell " + name + ".";
-  }
-}
-
-var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales };
-
-console.log(car.myCar);   // Saturn
-console.log(car.getCar);  // Honda
-console.log(car.special); // Toyota
-
- -

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

- -
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
-
-console.log(car.manyCars.b); // Jeep
-console.log(car[7]); // Mazda
-
- -

Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript {{Glossary("Identifier","identifier")}} or number, it must be enclosed in quotes. Property names that are not valid identifiers also cannot be accessed as a dot (.) property, but can be accessed and set with the array-like notation("[]").

- -
var unusualPropertyNames = {
-  "": "An empty string",
-  "!": "Bang!"
-}
-console.log(unusualPropertyNames."");   // SyntaxError: Unexpected string
-console.log(unusualPropertyNames[""]);  // An empty string
-console.log(unusualPropertyNames.!);    // SyntaxError: Unexpected token !
-console.log(unusualPropertyNames["!"]); // Bang!
- -

In ES2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

- -
var obj = {
-    // __proto__
-    __proto__: theProtoObj,
-    // Shorthand for ‘handler: handler’
-    handler,
-    // Methods
-    toString() {
-     // Super calls
-     return "d " + super.toString();
-    },
-    // Computed (dynamic) property names
-    [ 'prop_' + (() => 42)() ]: 42
-};
- -

Please note:

- -
var foo = {a: "alpha", 2: "two"};
-console.log(foo.a);    // alpha
-console.log(foo[2]);   // two
-//console.log(foo.2);  // Error: missing ) after argument list
-//console.log(foo[a]); // Error: a is not defined
-console.log(foo["a"]); // alpha
-console.log(foo["2"]); // two
-
- -

RegExp literals

- -

A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.

- -
var re = /ab+c/;
- -

String literals

- -

A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:

- -
"foo"
-'bar'
-"1234"
-"one line \n another line"
-"John's cat"
-
- -

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal:

- -
console.log("John's cat".length)
-// Will print the number of symbols in the string including whitespace.
-// In this case, 10.
-
- -

In ES2015, template literals are also available. Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.

- -
// Basic literal string creation
-`In JavaScript '\n' is a line-feed.`
-
-// Multiline strings
-`In JavaScript template strings can run
- over multiple lines, but double and single
- quoted strings cannot.`
-
-// String interpolation
-var name = "Bob", time = "today";
-`Hello ${name}, how are you ${time}?`
-
-// Construct an HTTP request prefix is used to interpret the replacements and construction
-POST`http://foo.org/bar?a=${a}&b=${b}
-     Content-Type: application/json
-     X-Credentials: ${credentials}
-     { "foo": ${foo},
-       "bar": ${bar}}`(myOnReadyStateChangeHandler);
- -

You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on String objects.

- -

Using special characters in strings

- -

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

- -
"one line \n another line"
-
- -

The following table lists the special characters that you can use in JavaScript strings.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Table: JavaScript special characters

-
CharacterMeaning
\0Null Byte
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.
\u{XXXXX}Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.
- -

Escaping characters

- -

For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

- -

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-console.log(quote);
-
- -

The result of this would be:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
-
- -

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

- -
var home = "c:\\temp";
-
- -

You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.

- -
var str = "this string \
-is broken \
-across multiple\
-lines."
-console.log(str);   // this string is broken across multiplelines.
-
- -

Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line:

- -
var poem =
-"Roses are red,\n\
-Violets are blue.\n\
-Sugar is sweet,\n\
-and so is foo."
-
- -

More information

- -

This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:

- - - -

In the next chapter, we will have a look at control flow constructs and error handling.

- -

{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

diff --git a/files/fa/web/javascript/guide/index.html b/files/fa/web/javascript/guide/index.html deleted file mode 100644 index ec38190108..0000000000 --- a/files/fa/web/javascript/guide/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: راهنمای جاوا اسکریپت -slug: Web/JavaScript/Guide -translation_of: Web/JavaScript/Guide -original_slug: Web/JavaScript/راهنما ---- -

{{jsSidebar("JavaScript Guide")}}

- -
-

راهنمای javascript یک مرور اجمالی بر روی این زبان داشته و به شما طریقه استفاده از جاوا اسکریپت را نشان می دهد.  اگر می خواهید به طور کلی برنامه نویسی یا جاوا اسکریپت را شروع کنید, از مقالات ما در محیط آموزشی کمک بگیرید. اگر به اطلاعات کامل درباره ویژگی های یک زبان نیاز دارید، نگاهی به مرجع جاوا اسکریپت داشته باشید

-
- - - - - -

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git a/files/fa/web/javascript/guide/introduction/index.html b/files/fa/web/javascript/guide/introduction/index.html deleted file mode 100644 index 8b047be839..0000000000 --- a/files/fa/web/javascript/guide/introduction/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: مقدمه -slug: Web/JavaScript/Guide/Introduction -tags: - - اکما اسکریپت - - جاوا اسکریپت -translation_of: Web/JavaScript/Guide/Introduction -original_slug: Web/JavaScript/راهنما/مقدمه ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
- -

در این فصل به مباحث مقدماتی جاوا اسکریپت پرداخته و برخی از مفاهیم اساسی آن را بیان می کنیم . 

- -

آنچه که شما باید از قبل بدانید

- -

این آموزش فرض را بر این گرفته که شما پیش زمینه های زیر را دارا هستید:

- - - -

مقداری تجربه ی برنامه نویسی . اگر شما به تازگی وارد برنامه نویسی شده اید ، سعی کنید ابتدا از لینک های آموزشی که در صفحه ی اصلی هست به لینک درباره ی جاوا اسکریپت بروید.

- -

کجا اطلاعات جاوا اسکریپت را پیدا کنید

- -

مستندات جاوا اسکریپت در MDN شامل موارد زیر است:

- -
    -
  1. یادگیری وب: اطلاعاتی را برای افراد تازه کار فراهم می کند و همچنین مفاهیم پایه برنامه نویسی و اینترنت را معرفی می کند
  2. -
  3. راهنمای جاوا اسکریپت: (این راهنمایی) یک دیدکلی را از زبان جاوا اسکریپت و اشیای آن ارائه می کند
  4. -
  5. مرجع جاوا اسکریپت: یک مرجع همراه با جزئیات برای زبان جاوا اسکریپت فراهم می کند
  6. -
- -

جاوا اسکریپت چیست؟

- -

جاوا اسکریپت یک زبان با بسترمتقاطع(چند پلتفرمی) و شی گرای اسکریپتی است. این زبان کوچک و سبک است. در محیط میزبان (برای مثال یک مرورگر) جاوا اسکریپت می تواند به اشیای محیط متصل شده و کنترل به وسیله برنامه نویسی را برای آن محیط فراهم می کند.

- -

جاوا اسکریپت شامل یک کتابخانه استاندارد اشیا است مانند Array، Date و Math، مجموعه پایه ای از عناصر زبان مثل عملگرها، ساختارهای کنترلی و عبارات. هسته ی زبان جاوا اسکریپت می تواند برای اهداف مختلفی توسعه داده شود. برای این منظور از جاوا اسکریپت به همراه اشیایی اضافی استفاده می شود برای مثال:

- - - -

جاوا اسکریپت و جاوا

- -

جاوااسکریپت و جاوا از بعضی جهات با هم مشابه

- -

In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.

- -

JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.

- -

Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.

- -

In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript compared to Java
JavaScriptJava
Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically.Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.
Variable data types are not declared (dynamic typing).Variable data types must be declared (static typing).
Cannot automatically write to hard disk.Can automatically write to hard disk.
- -

For more information on the differences between JavaScript and Java, see the chapter Details of the object model.

- -

مشخصات جاوا اسکریپت و اکما اسکریپت

- -

جاوا اسکریپت در Ecma International استاندارد شده است —اتحادیه اروپا برای استاندارد سازی سیستم های اطلاعاتی و ارتباطی (ECMA مخفف انجمن سازندگان کامپیوتری اروپا) بود تا یک زبان برنامه نویسی استاندارد مبتنی بر جاوا اسکریپت را ارائه کند.

- -

این نسخه استاندارد از جاوا اسکریپت، به نام اکما اسکریپت ، در تمامی برنامه هایی که از استاندارد پشتیبانی می کنند، یکسان عمل می کند. شرکت ها می توانند از استاندارد زبان باز برای توسعه جاوا اسکریپت خود استفاده کنند. استاندارد اکما اسکریپت در مشخصات ECMA-262 مستند شده است. تازه ها در جاوا اسکریپت را برای کسب اطلاعات بیشتر در مورد نسخه های مختلف نسخه های خاص جاوا اسکریپت و اکما اسکریپت مشاهده کنید.

- -

The ECMA-262 standard is also approved by the ISO (International Organization for Standardization) as ISO-16262. You can also find the specification on the Ecma International website. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the World Wide Web Consortium (W3C) and/or WHATWG (Web Hypertext Application Technology Working Group). The DOM defines the way in which HTML document objects are exposed to your script. To get a better idea about the different technologies that are used when programming with JavaScript, consult the article JavaScript technologies overview.

- -

مستندات جاوا اسکریپت در مقایسه با مشخصات اکما اسکریپت

- -

مشخصات اکما اسکریپت مجموعه ای از الزامات برای پیاده سازی اکما اسکریپت است؛ اگر شما می خواهید ویژگی های زبان سازگار با استاندارد را در پیاده سازی اکما اسکریپت یا موتور خود (مانند SpiderMonkey در فایرفاکس یا v8 در Chrome) پیاده سازی کنید، مفید است.

- -

The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.

- -

The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.

- -

The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.

- -

شروع با جاوا اسکریپت

- -

Getting started with JavaScript is easy: all you need is a modern Web browser. This guide includes some JavaScript features which are only currently available in the latest versions of Firefox, so using the most recent version of Firefox is recommended.

- -

There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.

- -

کنسول وب

- -

The Web Console shows you information about the currently loaded Web page, and also includes a command line that you can use to execute JavaScript expressions in the current page.

- -

To open the Web Console (Ctrl+Shift+K), select "Web Console" from the "Developer" menu, which is under the "Tools" menu in Firefox. It appears at the bottom of the browser window. Along the bottom of the console is a command line that you can use to enter JavaScript, and the output appears in the pane above:

- -

- -

Scratchpad

- -

The Web Console is great for executing single lines of JavaScript, but although you can execute multiple lines, it's not very convenient for that, and you can't save your code samples using the Web Console. So for more complex examples Scratchpad is a better tool.

- -

To open Scratchpad (Shift+F4), select "Scratchpad" from the "Developer" menu, which is under the menu in Firefox. It opens in a separate window and is an editor that you can use to write and execute JavaScript in the browser. You can also save scripts to disk and load them from disk.

- -

- -

Hello world

- -

To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:

- -
function greetMe(yourName) {
-  alert("Hello " + yourName);
-}
-
-greetMe("World");
-
- -

Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!

- -

In the following pages, this guide will introduce you to the JavaScript syntax and language features, so that you will be able to write more complex applications.

- -

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

diff --git a/files/fa/web/javascript/index.html b/files/fa/web/javascript/index.html deleted file mode 100644 index 2d8a11b00f..0000000000 --- a/files/fa/web/javascript/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: جاوا اسکریپت -slug: Web/JavaScript -tags: - - JavaScript - - Landing - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript ---- -
یک معرفی مجدد برای جاوااسکریپت
-یک بررسی کلی برا آن‌هایی که فکر می‌کنند در مورد جاوااسکریپت می‌دانند
- -

{{JsSidebar}}

- -

JavaScript® (اغلب به JS مخفف می‌شود) سبک، مفسر، زبان شی‌گرا شده با first-class functions، به عنوان زبان اسکریپت نویسی برای صفحات وب شناخته شده است، اما در خیلی از محیط‌های غیر مرورگری مانند node.js یا Apache CouchDB نیز استفاده شده است. زبان اسکریت نویسی آن مبتنی بر نمونه است، چند نمونه که پویا است، نوع امن و از شی گرایی پشتیبانی می‌کند، سبک ‌های برنامه نویسی تابعی را دارد. اطلاعات بیشتر را می‌توانید از صفحه درباره جاوااسکریپت مشاهده نمایید.

- -

استاندارد جاوااسکریپت اکمااسکریپت (ECMAScript) است که از سال ۲۰۱۲ تمامی مرورگر‌های مدرن استاندارد اکمااسکریپت نسخه ۵.۱ را به صورت کامل پشتیبانی می‌کنند، همچنین مرورگر‌های قدیمی‌تر نسخه ۳ از اکمااسکریپت را پشتیبانی می‌کنند. از ماه June سال ۲۰۱۵ اکمااسکریپت ۶ (ES6) یا همان اکمااسکریپت ۲۰۱۵ (ES2015) مورد قبول واقع شده است. توضیحات تکمیلی در مورد اکمااسکریپت ۶ را می توانید در dedicated wiki مشاهده نمایید.

- -

این بخش از سایت به زبان جاوااسکریپت اختصاص داده شده است، قسمت‌هایی که مختص به صفحات وب، یا دیگر محیط‌های میزبانی نیست. برای اطلاعات در مورد API‌های خاص برای صفحات وب، لطفا DOM را ببینید. در مورد این‌که چگونه DOM وJavaScript با همدیگر مناسب هستند در مرجع DOM اطلاعات بیشتری را بخوانید.

- -

JavaScript به صورت «جاواسکریپت» خوانده می‌شود، ولی در فارسی به صورت «جاوااسکریپت» ترجمه می‌شود و اگر به صورت «جاوا اسکریپت» ترجمه شود اشتباه است چون دو کلمه جدا از هم نیست و اگر به صورت دو کلمه جدا نوشته شود خطلاهای نگارشی ایجاد می‌شود، به طور مثال ممکن است کلمه جاوا در انتهای خط و کلمه اسکریپت در ابتدای خط بعدی نوشته شود.

- -
-
-

مستندات

- -
-
راهنمای جاوااسکریپت
-
اگر شما در جاوااسکریپت تازه‌کار هستید، باید این راهنما را بخوانید.
-
مرجع جاوااسکریپت
-
این مرجع جاوااسکریپت شامل مستندات کاملی برای جاوااسکریپت نسخه ۱.۵ و به‌روزرسانی‌های آن است.
-
- -

مقالات معرفی

- -
-
نمای کلی تکنولوژی‌های جاوااسکریپت
-
آشنایی با چشم انداز جاوااسکریپت برای مرورگر
-
- -

مقالات پیشرفته

- -
-
ساختارهای داده‌ای جاوااسکریپت
-
نمای کلی ساختارهای داده‌ای قابل دسترس در جاپااسکریپت
-
وراثت و زنجیره نمونه
-
توضیح ارث‌بری مبتنی بر نمونه که به‌صورت گسترده‌ای اشتباده و ناچیز شمرده شده است
-
- -

مقالات دیگر

- -
-
آموزش بوم نقاشی
-
<canvas> یک المان HTML5 است که برای رسم گرافیک‌ها با استفاده از اسکریپت نویسی استفاده می‌شود. آن می‌تواند، برای مثال برای رسم گرافیک‌ها، ترکیب عکس و یا انجام ساده (و نه خیلی ساده) انیمیشن‌ها استفاده شود.
-
مراجع زبان جاوااسکریپت
-
شرح زبان جاوااسکریپت استاندارد.
-
مستندات پشتیبانی استانداردهای اینترنت اکسپلورر
-
مایکروسافت مستنداتی منتشر کرده است که "تغییرات، توضیحات، و الحاقیات برخی استانداردهای مورد تایید پشتیبانی شده توسط اینترنت اکسپلورر." را شرح می‌دهد، بعضی از آن‌ها مربوط به جاوااسکریپت هستند:
-
- -
-
- -

View All...

-
- -
-

ابزارها & منابع پیشرفته

- -
    -
  • ابزارهای توسعه فایرفاکس - ابزارهای عالی تعبیه شده در فایرفاکس.
  • -
  • Koding پلت فرم توسعه آن‌لاین با پشتیبانی جاوااسکریپت
  • -
  • LearnStreet - آموزش‌ها و تمرین‌های عملی رایگان آن‌لاین.
  • -
  • Codecademy - دوره جاوااسکریپت رایگان با مشکلات تعاملی
  • -
  • Code School - یادگیری بوسیله انجام دادن، چندین دوره جاو.ا اسکریپت
  • -
  • Frontend Masters - فیلم‌های کارگاه آموزشی جاوااسکریپت و توسعه وب نهایی
  • -
  • Let’s Code: Test-Driven JavaScript - سری‌های ضبط خیلی دقیق صفحه، توسعه حرفه‌ای جاوااسکریپت
  • -
  • Idiomatic.js - اصول نوشتن جاوااسکریپت استوار، اصطلاحی
  • -
  • Memory Management in JavaScript . نمای کلی از چگونگی عملکرد حافظه در جاوااسکریپت
  • -
  • Firebug - اشکال‌زدایی و پروفایلینگ جاوااسکریپت
  • -
  • Venkman - دیباگر جاوااسکریپت
  • -
  • JavaScript Shells - تست قطعه کدهای کوچک
  • -
  • JSHint - ابزاری که در تشخیص خطا و مشکلات بالقوه در کد جاوااسکریپت شما کمک می‌کند
  • -
  • JSLint - چک کننده نحو، در برابر اعمال بد هشدار می‌دهد
  • -
  • JSDoc - تولید مستندات از کد
  • -
  • JavaScript Redirect - ابزار تغییر مسیر پیشرفته جاوااسکریپت
  • -
  • Aptana Studio - IDE متن باز با پشتیبانی آژاکس و جاوااسکریپت (بر اساس eclipse)
  • -
  • Netbeans - IDE متن باز شامل پشتیبانی پیچیده از جاوااسکریپت
  • -
  • Eclipse - IDE متن باز شامل جعبه ابزار توسعه جاوااسکریپت
  • -
  • Cloud9 IDE - IDE متن باز که در مرورگر اجرا شده با قابلیت پشتیبانی از جاوااسکریپت و Node.js
  • -
  • Pretty Diff - یک ابزار متفاوت برای مقایسه کد خرد شده با کد معمولی
  • -
  • Object Playground - ابزاری برای درک شی‌گرایی جاوااسکریپت
  • -
  • Extension Developer's Extension - محیط و شل JS را ارایه می‌دهد
  • -
  • BoilerplateJS - مرجع معماری برای پروژه‌های جاوااسکریپت در مقیاس بزرگ
  • -
  • JSFiddle - مورد استفاده برای آزمایش و اصلاح وب سایت با جاوااسکریپت آن‌لاین. 
  • -
  • دیگر ابزارهای جاوااسکریپت
  • -
- -

نمایش همه...

- -

دیگر منابع

- -
-
JavaScript Garden
-
سایتی با اطلاعات مفید در مورد قطعات داخلی‌تر جاوااسکریپت.
-
JSWiki
-
یک ویکی مبتنی بر Githubکه منابع و کتابخانه‌ها را ایندکس گذاری کرده است.
-
Stack Overflow
-
یک سایت همکاری ساخته و نگه‌داری شده Q&A و می‌توانید برای جواب سوال خودرا در آن جستجو کنید. اگر جواب سوال خودرا پیدا نکردید می‌توانید سوال خودرا در آن‌جا مطرح کنید.
-
Pineapple · JavaScript
-
یک پایگاه داده بزرگ از آموزش و منابع حال حاضر جاوااسکریپت.
-
Life of JavaScript
-
منابع عالی در مورد جاوااسکریپت شامل کتاب، ارایه‌ها، فیلم‌ها، فیدها، سایت‌ها، کتابخانه‌ها، محیط‌های کاری، ابزارها که در یک‌جا جمع آموری شده است.
-
- - - - -
-
diff --git a/files/fa/web/javascript/inheritance_and_the_prototype_chain/index.html b/files/fa/web/javascript/inheritance_and_the_prototype_chain/index.html deleted file mode 100644 index 73aac306f7..0000000000 --- a/files/fa/web/javascript/inheritance_and_the_prototype_chain/index.html +++ /dev/null @@ -1,533 +0,0 @@ ---- -title: ارث بری و پروتوتایپ در جاوا اسکریپت -slug: Web/JavaScript/Inheritance_and_the_prototype_chain -translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain ---- -
{{jsSidebar("Advanced")}}
- -

جاوا اسکریپت ممکن است برای کسانی که با زبانهای شی گرا آشنایی دارند کمی گیج کننده باشد (زبانهایی مثل Java یاC++), بدلیل اینکه این زبان پویاست و کمپایل نمیشود و همچنین مفهومی به نام class را ندارد (البته واژهclass در نسخه ES2015 معرفی شد, ولی در واقع فقط ظاهر قضیه عوض شده و در باطن کماکان ارث بری در جاوااسکریپت همان سیستم پروتوتایپ است).

- -

وقتی صحبت از وراثت باشد جاوا اسکریپت فقط یک شی دارد : objects.

- -

هر آبجکت در جاوااسکریپت یک مشخصه (property ) مخفی دارد که به یک شی دیگر در رم اشاره میکند که این شی دوم همان پروتوتایپِ شی اول است. 

- -

 ، این پروتوتایپ هم برای خودش یک پروتوتایپ دارد و ... الی آخر . تا جایی که بالاترین شی در زنجیره پروتوتایپش null  است . از آنجایی که null  پروتوتایپ ندارد لذا این شی آخر حلقه در این زنجیره است . به این زنجیره ، زنجیره پروتوتایپ میگویند

- -

تقریبا همه اشیا در جاوا اسکریپت فرزند {{jsxref("Object")}} هستند که این شیء ، بالاترین شی در زنجیره پروتوتایپ است

- -

در حالیکه ممکن است این به عنوان یکی از ضعف های جاوااسکریپت به نظر بیاد ولی در واقع مدل ارث بری پروتوتایپی از مدل سنتی قدرتمند تر است . به طور مثال ساختن مدل سنتی ارث بری با استفاده از مدل پروتوتایپی کار بسیار ساده ای است.

- -

ارث بری با زنجیره پروتوتایپ

- -

ارث بری خصوصیات (properties)

- -

اشیا در جاوا اسکریپت مثل کیف هایی پر از خصوصیات(properties) هستند . اشیا در این زبان همونطور که گفته شد یک لینک به پروتوتایپ خودشون هم دران . وقتی میخواهیم به یک خصوصیت از یک شی دسترسی پیدا کنیم اگر آن خصوصیت در خود شی پیدا نشد جاوا اسکریپت در پروتوتایپ دنبال آن خصوصیت میگردد ، اگر در آنجاهم نشد در پروتوتایپِ مربوط به آن پروتوتایپ و به همین ترتیب تا آخر زنجیره پروتوتایپ پیش میرود که یا property فراخوانی شده پیدا شود یا به انتهای زنجیره برسیم و جستجو تمام شود.

- -
-

 در کدهای اکمااسکریپت زیر منظور از  someObject.[[Prototype]]  پروتوتایپِ   someObject  است . از ECMAScript 2015 پروتوتایپ )[[Prototype]]( از طریق {{jsxref("Object.getPrototypeOf()")}} و یا {{jsxref("Object.setPrototypeOf()")}} قابل دسترسی است . این روش معادل است با استفاده از  __proto__ که روشی استاندارد نیست ولی در اکثر مرورگرها پیاده سازی شده و قابل استفاده است.

- -

این رو نباید با func.prototype که در حقیقت یک property از توابع هست اشتباه کنیم ، که کاربردش هم جایی هست که بخواهیم همه اشیایی که توسط function مورد نظر ساخته شدن ، همه دارای پروتایپ دلخواه ما باشن

- -

Object.prototype در واقع {{jsxref("Object")}} در زنجیره پروتوتایپ است

-
- -

وقتی ما یک propertyاز یک شی رو فراخونی میکنیم اتفاقی که میافته به این صورته :

- -
// Let's create an object o from function f with its own properties a and b:
-let f = function () {
-   this.a = 1;
-   this.b = 2;
-}
-let o = new f(); // {a: 1, b: 2}
-
-// add properties in f function's prototype
-f.prototype.b = 3;
-f.prototype.c = 4;
-
-// do not set the prototype f.prototype = {b:3,c:4}; this will break the prototype chain
-// o.[[Prototype]] has properties b and c.
-// o.[[Prototype]].[[Prototype]] is Object.prototype.
-// Finally, o.[[Prototype]].[[Prototype]].[[Prototype]] is null.
-// This is the end of the prototype chain, as null,
-// by definition, has no [[Prototype]].
-// Thus, the full prototype chain looks like:
-// {a: 1, b: 2} ---> {b: 3, c: 4} ---> Object.prototype ---> null
-
-console.log(o.a); // 1
-// Is there an 'a' own property on o? Yes, and its value is 1.
-
-console.log(o.b); // 2
-// Is there a 'b' own property on o? Yes, and its value is 2.
-// The prototype also has a 'b' property, but it's not visited.
-// This is called "property shadowing."
-
-console.log(o.c); // 4
-// Is there a 'c' own property on o? No, check its prototype.
-// Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4.
-
-console.log(o.d); // undefined
-// Is there a 'd' own property on o? No, check its prototype.
-// Is there a 'd' own property on o.[[Prototype]]? No, check its prototype.
-// o.[[Prototype]].[[Prototype]] is null, stop searching,
-// no property found, return undefined.
-
- -

Code Link

- -

Setting a property to an object creates an own property. The only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter.

- -

Inheriting "methods"

- -

JavaScript does not have "methods" in the form that class-based languages define them. In JavaScript, any function can be added to an object in the form of a property. An inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of method overriding).

- -

When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.

- -
var o = {
-  a: 2,
-  m: function() {
-    return this.a + 1;
-  }
-};
-
-console.log(o.m()); // 3
-// When calling o.m in this case, 'this' refers to o
-
-var p = Object.create(o);
-// p is an object that inherits from o
-
-p.a = 4; // creates a property 'a' on p
-console.log(p.m()); // 5
-// when p.m is called, 'this' refers to p.
-// So when p inherits the function m of o,
-// 'this.a' means p.a, the property 'a' of p
-
-
-
- -

Using prototypes in JavaScript

- -

Let's look at what happens behind the scenes in a bit more detail.

- -

In JavaScript, as mentioned above, functions are able to have properties. All functions have a special property named prototype. Please note that the code below is free-standing (it is safe to assume there is no other JavaScript on the webpage other than the below code). For the best learning experience, it is highly reccomended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigating to the "console" tab, copying-and-pasting in the below JavaScript code, and run it by pressing the Enter/Return key.

- -
function doSomething(){}
-console.log( doSomething.prototype );
-// It does not matter how you declare the function, a
-//  function in javascript will always have a default
-//  prototype property.
-var doSomething = function(){};
-console.log( doSomething.prototype );
-
- -

As seen above, doSomething() has a default prototype property, as demonstrated by the console. After running this code, the console should have displayed an object that looks similar to this.

- -
{
-    constructor: ƒ doSomething(),
-    __proto__: {
-        constructor: ƒ Object(),
-        hasOwnProperty: ƒ hasOwnProperty(),
-        isPrototypeOf: ƒ isPrototypeOf(),
-        propertyIsEnumerable: ƒ propertyIsEnumerable(),
-        toLocaleString: ƒ toLocaleString(),
-        toString: ƒ toString(),
-        valueOf: ƒ valueOf()
-    }
-}
- -

We can add properties to the prototype of doSomething(), as shown below.

- -
function doSomething(){}
-doSomething.prototype.foo = "bar";
-console.log( doSomething.prototype );
- -

This results in:

- -
{
-    foo: "bar",
-    constructor: ƒ doSomething(),
-    __proto__: {
-        constructor: ƒ Object(),
-        hasOwnProperty: ƒ hasOwnProperty(),
-        isPrototypeOf: ƒ isPrototypeOf(),
-        propertyIsEnumerable: ƒ propertyIsEnumerable(),
-        toLocaleString: ƒ toLocaleString(),
-        toString: ƒ toString(),
-        valueOf: ƒ valueOf()
-    }
-}
-
- -

We can now use the new operator to create an instance of doSomething() based on this prototype. To use the new operator, simply call the function normally except prefix it with new. Calling a function with the new operator returns an object that is an instance of the function. Properties can then be added onto this object.

- -

Try the following code:

- -
function doSomething(){}
-doSomething.prototype.foo = "bar"; // add a property onto the prototype
-var doSomeInstancing = new doSomething();
-doSomeInstancing.prop = "some value"; // add a property onto the object
-console.log( doSomeInstancing );
- -

This results in an output similar to the following:

- -
{
-    prop: "some value",
-    __proto__: {
-        foo: "bar",
-        constructor: ƒ doSomething(),
-        __proto__: {
-            constructor: ƒ Object(),
-            hasOwnProperty: ƒ hasOwnProperty(),
-            isPrototypeOf: ƒ isPrototypeOf(),
-            propertyIsEnumerable: ƒ propertyIsEnumerable(),
-            toLocaleString: ƒ toLocaleString(),
-            toString: ƒ toString(),
-            valueOf: ƒ valueOf()
-        }
-    }
-}
- -

As seen above, the __proto__ of doSomeInstancing is doSomething.prototype. But, what does this do? When you access a property of doSomeInstancing, the browser first looks to see if doSomeInstancing has that property.

- -

If doSomeInstancing does not have the property, then the browser looks for the property in the __proto__ of doSomeInstancing (a.k.a. doSomething.prototype). If the __proto__ of doSomeInstancing has the property being looked for, then that property on the __proto__ of doSomeInstancing is used.

- -

Otherwise, if the __proto__ of doSomeInstancing does not have the property, then the __proto__ of the __proto__ of doSomeInstancing is checked for the property. By default, the __proto__ of any function's prototype property is window.Object.prototype. So, the __proto__ of the __proto__ of doSomeInstancing (a.k.a. the __proto__ of doSomething.prototype (a.k.a. Object.prototype)) is then looked through for the property being searched for.

- -

If the property is not found in the __proto__ of the __proto__ of doSomeInstancing, then the __proto__ of the __proto__ of the __proto__ of doSomeInstancing is looked through. However, there is a problem: the __proto__ of the __proto__ of the __proto__ of doSomeInstancing does not exist. Then, and only then, after the entire prototype chain of __proto__'s is looked through, and there are no more __proto__s does the browser assert that the property does not exist and conclude that the value at the property is undefined.

- -

Let's try entering some more code into the console:

- -
function doSomething(){}
-doSomething.prototype.foo = "bar";
-var doSomeInstancing = new doSomething();
-doSomeInstancing.prop = "some value";
-console.log("doSomeInstancing.prop:      " + doSomeInstancing.prop);
-console.log("doSomeInstancing.foo:       " + doSomeInstancing.foo);
-console.log("doSomething.prop:           " + doSomething.prop);
-console.log("doSomething.foo:            " + doSomething.foo);
-console.log("doSomething.prototype.prop: " + doSomething.prototype.prop);
-console.log("doSomething.prototype.foo:  " + doSomething.prototype.foo);
- -

This results in the following:

- -
doSomeInstancing.prop:      some value
-doSomeInstancing.foo:       bar
-doSomething.prop:           undefined
-doSomething.foo:            undefined
-doSomething.prototype.prop: undefined
-doSomething.prototype.foo:  bar
- -

Different ways to create objects and the resulting prototype chain

- -

Objects created with syntax constructs

- -
var o = {a: 1};
-
-// The newly created object o has Object.prototype as its [[Prototype]]
-// o has no own property named 'hasOwnProperty'
-// hasOwnProperty is an own property of Object.prototype.
-// So o inherits hasOwnProperty from Object.prototype
-// Object.prototype has null as its prototype.
-// o ---> Object.prototype ---> null
-
-var b = ['yo', 'whadup', '?'];
-
-// Arrays inherit from Array.prototype
-// (which has methods indexOf, forEach, etc.)
-// The prototype chain looks like:
-// b ---> Array.prototype ---> Object.prototype ---> null
-
-function f() {
-  return 2;
-}
-
-// Functions inherit from Function.prototype
-// (which has methods call, bind, etc.)
-// f ---> Function.prototype ---> Object.prototype ---> null
-
- -

With a constructor

- -

A "constructor" in JavaScript is "just" a function that happens to be called with the new operator.

- -
function Graph() {
-  this.vertices = [];
-  this.edges = [];
-}
-
-Graph.prototype = {
-  addVertex: function(v) {
-    this.vertices.push(v);
-  }
-};
-
-var g = new Graph();
-// g is an object with own properties 'vertices' and 'edges'.
-// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.
-
- -

With Object.create

- -

ECMAScript 5 introduced a new method: {{jsxref("Object.create()")}}. Calling this method creates a new object. The prototype of this object is the first argument of the function:

- -
var a = {a: 1};
-// a ---> Object.prototype ---> null
-
-var b = Object.create(a);
-// b ---> a ---> Object.prototype ---> null
-console.log(b.a); // 1 (inherited)
-
-var c = Object.create(b);
-// c ---> b ---> a ---> Object.prototype ---> null
-
-var d = Object.create(null);
-// d ---> null
-console.log(d.hasOwnProperty);
-// undefined, because d doesn't inherit from Object.prototype
-
- -
-

With the class keyword

- -

ECMAScript 2015 introduced a new set of keywords implementing classes. The new keywords include {{jsxref("Statements/class", "class")}}, {{jsxref("Classes/constructor", "constructor")}}, {{jsxref("Classes/static", "static")}}, {{jsxref("Classes/extends", "extends")}}, and {{jsxref("Operators/super", "super")}}.

- -
'use strict';
-
-class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
-
-class Square extends Polygon {
-  constructor(sideLength) {
-    super(sideLength, sideLength);
-  }
-  get area() {
-    return this.height * this.width;
-  }
-  set sideLength(newLength) {
-    this.height = newLength;
-    this.width = newLength;
-  }
-}
-
-var square = new Square(2);
-
- -

Performance

- -

The lookup time for properties that are high up on the prototype chain can have a negative impact on the performance, and this may be significant in the code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain.

- -

Also, when iterating over the properties of an object, every enumerable property that is on the prototype chain will be enumerated. To check whether an object has a property defined on itself and not somewhere on its prototype chain, it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype. To give you a concrete example, let's take the above graph example code to illustrate it:

- -
console.log(g.hasOwnProperty('vertices'));
-// true
-
-console.log(g.hasOwnProperty('nope'));
-// false
-
-console.log(g.hasOwnProperty('addVertex'));
-// false
-
-console.log(g.__proto__.hasOwnProperty('addVertex'));
-// true
-
- -

hasOwnProperty is the only thing in JavaScript which deals with properties and does not traverse the prototype chain.

- -

Note: It is not enough to check whether a property is undefined. The property might very well exist, but its value just happens to be set to undefined.

-
- -

Bad practice: Extension of native prototypes

- -

One misfeature that is often used is to extend Object.prototype or one of the other built-in prototypes.

- -

This technique is called monkey patching and breaks encapsulation. While used by popular frameworks such as Prototype.js, there is still no good reason for cluttering built-in types with additional non-standard functionality.

- -

The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines, like Array.forEach.

- -

Summary of methods for extending the protoype chain

- -

Here are all 5 ways and their pros/cons. All of the examples listed below create exactly the same resulting inst object (thus logging the same results to the console), except in different ways for the purpose of illustration.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameExample(s)Pro(s)Con(s)
New-initialization -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = new foo;
-proto.bar_prop = "bar val";
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop);
-
-
Supported in every browser imaginable (support goes all the way back to IE 5.5!). Also, it is very fast, very standard, and very JIST-optimizable.In order to use this method, the function in question must be initialized. During this initialization, the constructor may store unique information that must be generated per-object. However, this unique information would only be generated once, potentially leading to problems. Additionally, the initialization of the constructor may put unwanted methods onto the object. However, both these are generally not problems at all (in fact, usually beneficial) if it is all your own code and you know what does what where.
Object.create -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = Object.create(
-  foo.prototype
-);
-proto.bar_prop = "bar val";
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop);
-
- -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = Object.create(
-  foo.prototype,
-  {
-    bar_prop: {
-      value: "bar val"
-    }
-  }
-);
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop)
-
Support in all in-use-today browsers which are all non-microsoft browsers plus IE9 and up. Allows the direct setting of __proto__ in a way that is one-time-only so that the browser can better optimize the object. Also allows the creation of objects without a prototype via Object.create(null).Not supported in IE8 and below. However, as Microsoft has discontinued extended support for systems running theses old browsers, this should not be a concern for most applications. Additionally, the slow object initialization can be a performance black hole if using the second argument because each object-descriptor property has its own separate descriptor object. When dealing with hundreds of thousands of object descriptors in the form of object, there can arise a serious issue with lag.
-

Object.setPrototypeOf

-
-
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = {
-  bar_prop: "bar val"
-};
-Object.setPrototypeOf(
-  proto, foo.prototype
-);
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop);
-
- -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto;
-proto=Object.setPrototypeOf(
-  { bar_prop: "bar val" },
-  foo.prototype
-);
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop)
-
Support in all in-use-today browsers which are all non-microsoft browsers plus IE9 and up. Allows the dynamic manipulation of an objects prototype and can even force a prototype on a prototype-less object created with Object.create(null).Should-be-depredicated and ill-performant. Making your Javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the specs. Not supported in IE8 and below.
__proto__ -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = {
-  bar_prop: "bar val";
-  __proto__: foo.prototype
-};
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop);
-
- -
-var inst = {
-  __proto__: {
-    bar_prop: "bar val",
-    __proto__: {
-      foo_prop: "foo val",
-      __proto__: Object
-    }
-  }
-};
-console.log(inst.foo_prop);
-console.log(inst.bar_prop)
-
Support in all in-use-today browsers which are all non-microsoft browsers plus IE11 and up. Setting __proto__ to something that is not an object only fails silently. It does not throw an exception.Grossly depredicated and non-performant. Making your Javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the specs. Not supported in IE10 and below.
- -

prototype and Object.getPrototypeOf

- -

JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object.

- -

You probably already noticed that our function A has a special property called prototype. This special property works with the JavaScript new operator. The reference to the prototype object is copied to the internal [[Prototype]] property of the new instance. For example, when you do var a1 = new A(), JavaScript (after creating the object in memory and before running function A() with this defined to it) sets a1.[[Prototype]] = A.prototype. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. This means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances, if you wanted to.

- -

If, in the example above, you do var a1 = new A(); var a2 = new A(); then a1.doSomething would actually refer to Object.getPrototypeOf(a1).doSomething, which is the same as the A.prototype.doSomething you defined, i.e. Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething.

- -

In short, prototype is for types, while Object.getPrototypeOf() is the same for instances.

- -

[[Prototype]] is looked at recursively, i.e. a1.doSomething, Object.getPrototypeOf(a1).doSomething, Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething etc., until it's found or Object.getPrototypeOf returns null.

- -

So, when you call

- -
var o = new Foo();
- -

JavaScript actually just does

- -
var o = new Object();
-o.[[Prototype]] = Foo.prototype;
-Foo.call(o);
- -

(or something like that) and when you later do

- -
o.someProp;
- -

it checks whether o has a property someProp. If not, it checks Object.getPrototypeOf(o).someProp, and if that doesn't exist it checks Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp, and so on.

- -

In conclusion

- -

It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features.

diff --git a/files/fa/web/javascript/reference/classes/index.html b/files/fa/web/javascript/reference/classes/index.html deleted file mode 100644 index e031309f9f..0000000000 --- a/files/fa/web/javascript/reference/classes/index.html +++ /dev/null @@ -1,418 +0,0 @@ ---- -title: Classes -slug: Web/JavaScript/Reference/Classes -tags: - - Classes - - Constructors - - ECMAScript 2015 - - Guide - - Inheritance - - Intermediate - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Classes ---- -
{{JsSidebar("Classes")}}
- -

Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 classalike semantics.

- -

Defining classes

- -

Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

- -

Class declarations

- -

One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Rectangle" here).

- -
class Rectangle {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
- -

Hoisting

- -

An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a {{jsxref("ReferenceError")}}:

- -
const p = new Rectangle(); // ReferenceError
-
-class Rectangle {}
-
- -

Class expressions

- -

A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) {{jsxref("Function.name", "name")}} property, though).

- -
// unnamed
-let Rectangle = class {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-console.log(Rectangle.name);
-// output: "Rectangle"
-
-// named
-let Rectangle = class Rectangle2 {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-console.log(Rectangle.name);
-// output: "Rectangle2"
-
- -
-

Note: Class expressions are subject to the same hoisting restrictions as described in the Class declarations section.

-
- -

Class body and method definitions

- -

The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructor.

- -

Strict mode

- -

The body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript.

- -

Constructor

- -

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A {{jsxref("SyntaxError")}} will be thrown if the class contains more than one occurrence of a constructor method.

- -

A constructor can use the super keyword to call the constructor of the super class.

- -

Prototype methods

- -

See also method definitions.

- -
class Rectangle {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-  // Getter
-  get area() {
-    return this.calcArea();
-  }
-  // Method
-  calcArea() {
-    return this.height * this.width;
-  }
-}
-
-const square = new Rectangle(10, 10);
-
-console.log(square.area); // 100
- -

Static methods

- -

The static keyword defines a static method for a class. Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.

- -
class Point {
-  constructor(x, y) {
-    this.x = x;
-    this.y = y;
-  }
-
-  static distance(a, b) {
-    const dx = a.x - b.x;
-    const dy = a.y - b.y;
-
-    return Math.hypot(dx, dy);
-  }
-}
-
-const p1 = new Point(5, 5);
-const p2 = new Point(10, 10);
-p1.distance; //undefined
-p2.distance; //undefined
-
-console.log(Point.distance(p1, p2)); // 7.0710678118654755
-
- -

Binding this with prototype and static methods

- -

When a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method. This behavior will be the same even if the "use strict" directive isn't present, because code within the class body's syntactic boundary is always executed in strict mode.

- -
class Animal {
-  speak() {
-    return this;
-  }
-  static eat() {
-    return this;
-  }
-}
-
-let obj = new Animal();
-obj.speak(); // the Animal object
-let speak = obj.speak;
-speak(); // undefined
-
-Animal.eat() // class Animal
-let eat = Animal.eat;
-eat(); // undefined
- -

If we rewrite the above using traditional function-based syntax in non–strict mode, then this method calls is automatically bound to the initial this value, which by default is the global object. In strict mode, autobinding will not happen; the value of this remains as passed.

- -
function Animal() { }
-
-Animal.prototype.speak = function() {
-  return this;
-}
-
-Animal.eat = function() {
-  return this;
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // global object (in non–strict mode)
-
-let eat = Animal.eat;
-eat(); // global object (in non-strict mode)
-
- -

Instance properties

- -

Instance properties must be defined inside of class methods:

- -
class Rectangle {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
- -

Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:

- -
Rectangle.staticWidth = 20;
-Rectangle.prototype.prototypeWidth = 25;
-
- -

Field declarations

- -
-

Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like Babel.

-
- -

Public field declarations

- -

With the JavaScript field declaration syntax, the above example can be written as:

- -
class Rectangle {
-  height = 0;
-  width;
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
-
- -

By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.

- -

As seen above, the fields can be declared with or without a default value.

- -

See public class fields for more information.

- -

Private field declarations

- -

Using private fields, the definition can be refined as below.

- -
class Rectangle {
-  #height = 0;
-  #width;
-  constructor(height, width) {
-    this.#height = height;
-    this.#width = width;
-  }
-}
-
- -

It's an error to reference private fields from outside of the class; they can only be read or written within the class body. By defining things which are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may change version to version.

- -
-

Private fields can only be declared up-front in a field declaration.

-
- -

Private fields cannot be created later through assigning to them, the way that normal properties can.

- -

For more information, see private class fields.

- -

Sub classing with extends

- -

The extends keyword is used in class declarations or class expressions to create a class as a child of another class.

- -
class Animal {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(`${this.name} makes a noise.`);
-  }
-}
-
-class Dog extends Animal {
-  constructor(name) {
-    super(name); // call the super class constructor and pass in the name parameter
-  }
-
-  speak() {
-    console.log(`${this.name} barks.`);
-  }
-}
-
-let d = new Dog('Mitzie');
-d.speak(); // Mitzie barks.
-
- -

If there is a constructor present in the subclass, it needs to first call super() before using "this".

- -

One may also extend traditional function-based "classes":

- -
function Animal (name) {
-  this.name = name;
-}
-
-Animal.prototype.speak = function () {
-  console.log(`${this.name} makes a noise.`);
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(`${this.name} barks.`);
-  }
-}
-
-let d = new Dog('Mitzie');
-d.speak(); // Mitzie barks.
-
-// For similar methods, the child's method takes precedence over parent's method
- -

Note that classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object, you can instead use {{jsxref("Object.setPrototypeOf()")}}:

- -
const Animal = {
-  speak() {
-    console.log(`${this.name} makes a noise.`);
-  }
-};
-
-class Dog {
-  constructor(name) {
-    this.name = name;
-  }
-}
-
-// If you do not do this you will get a TypeError when you invoke speak
-Object.setPrototypeOf(Dog.prototype, Animal);
-
-let d = new Dog('Mitzie');
-d.speak(); // Mitzie makes a noise.
-
- -

Species

- -

You might want to return {{jsxref("Array")}} objects in your derived array class MyArray. The species pattern lets you override default constructors.

- -

For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The {{jsxref("Symbol.species")}} symbol lets you do this:

- -
class MyArray extends Array {
-  // Overwrite species to the parent Array constructor
-  static get [Symbol.species]() { return Array; }
-}
-
-let a = new MyArray(1,2,3);
-let mapped = a.map(x => x * x);
-
-console.log(mapped instanceof MyArray); // false
-console.log(mapped instanceof Array);   // true
-
- -

Super class calls with super

- -

The super keyword is used to call corresponding methods of super class. This is one advantage over prototype-based inheritance.

- -
class Cat {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(`${this.name} makes a noise.`);
-  }
-}
-
-class Lion extends Cat {
-  speak() {
-    super.speak();
-    console.log(`${this.name} roars.`);
-  }
-}
-
-let l = new Lion('Fuzzy');
-l.speak();
-// Fuzzy makes a noise.
-// Fuzzy roars.
-
- -

Mix-ins

- -

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

- -

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

- -
let calculatorMixin = Base => class extends Base {
-  calc() { }
-};
-
-let randomizerMixin = Base => class extends Base {
-  randomize() { }
-};
-
- -

A class that uses these mix-ins can then be written like this:

- -
class Foo { }
-class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.classes")}}

- -

Re-running a class definition

- -

A class can't be redefined. Attempting to do so produces a SyntaxError.

- -

If you're experimenting with code in a web browser, such as the Firefox Web Console (Tools > Web Developer > Web Console) and you 'Run' a definition of a class with the same name twice, you'll get a SyntaxError: redeclaration of let ClassName;. (See further discussion of this issue in bug 1428672.) Doing something similar in Chrome Developer Tools gives you a message like Uncaught SyntaxError: Identifier 'ClassName' has already been declared at <anonymous>:1:1.

- -

See also

- - diff --git a/files/fa/web/javascript/reference/errors/index.html b/files/fa/web/javascript/reference/errors/index.html deleted file mode 100644 index c295fccea6..0000000000 --- a/files/fa/web/javascript/reference/errors/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: JavaScript error reference -slug: Web/JavaScript/Reference/Errors -tags: - - Debugging - - Error - - Errors - - Exception - - JavaScript - - NeedsTranslation - - TopicStub - - exceptions -translation_of: Web/JavaScript/Reference/Errors ---- -

{{jsSidebar("Errors")}}

- -

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

- -

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

- -

List of errors

- -

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

- -

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

- -

See also

- - diff --git a/files/fa/web/javascript/reference/errors/too_much_recursion/index.html b/files/fa/web/javascript/reference/errors/too_much_recursion/index.html deleted file mode 100644 index 02a8d54c45..0000000000 --- a/files/fa/web/javascript/reference/errors/too_much_recursion/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: 'InternalError: too much recursion' -slug: Web/JavaScript/Reference/Errors/Too_much_recursion -translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
Error: Out of stack space (Edge)
-InternalError: too much recursion (Firefox)
-RangeError: Maximum call stack size exceeded (Chrome)
-
- -

Error type

- -

{{jsxref("InternalError")}}.

- -

What went wrong?

- -

A function that calls itself is called a recursive function. Once a condition is met, the function stops calling itself. This is called a base case.

- -

In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.

- -

Examples

- -

This recursive function runs 10 times, as per the exit condition.

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" is the exit condition
-    return;
-  // do stuff
-  loop(x + 1); // the recursive call
-}
-loop(0);
- -

Setting this condition to an extremely high value, won't work:

- -
function loop(x) {
-  if (x >= 1000000000000)
-    return;
-  // do stuff
-  loop(x + 1);
-}
-loop(0);
-
-// InternalError: too much recursion
- -

This recursive function is missing a base case. As there is no exit condition, the function will call itself infinitely.

- -
function loop(x) {
- // The base case is missing
-
-loop(x + 1); // Recursive call
-}
-
-loop(0);
-
-// InternalError: too much recursion
- -

Class error: too much recursion

- -
class Person{
-	constructor(){}
-	set name(name){
-		this.name = name; // Recursive call
-	}
-}
-
-
-const tony = new Person();
-tony.name = "Tonisha"; // InternalError: too much recursion
-
- -

When a value is assigned to the property name (this.name = name;) JavaScript needs to set that property. When this happens, the setter function is triggered.

- -
set name(name){
-	this.name = name; // Recursive call
-}
-
- -
-

In this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle. This causes the function to call itself, again and again, making it infinitely recursive.

-
- -

This issue also appears if the same variable is used in the getter.

- -
get name(){
-	return this.name; // Recursive call
-}
-
- -

To avoid this problem, make sure that the property being assigned to inside the setter function is different from the one that initially triggered the setter.The same goes for the getter.

- -
class Person{
-	constructor(){}
-	set name(name){
-		this._name = name;
-	}
-	get name(){
-		return this._name;
-	}
-}
-const tony = new Person();
-tony.name = "Tonisha";
-console.log(tony);
-
- -

See also

- - diff --git a/files/fa/web/javascript/reference/errors/unexpected_token/index.html b/files/fa/web/javascript/reference/errors/unexpected_token/index.html deleted file mode 100644 index 77fa2e06c5..0000000000 --- a/files/fa/web/javascript/reference/errors/unexpected_token/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: 'SyntaxError: Unexpected token' -slug: Web/JavaScript/Reference/Errors/Unexpected_token -translation_of: Web/JavaScript/Reference/Errors/Unexpected_token ---- -
- -
- -
-

{{jsSidebar("Errors")}}

-
- -

The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

- -

Message

- -
SyntaxError: expected expression, got "x"
-SyntaxError: expected property name, got "x"
-SyntaxError: expected target, got "x"
-SyntaxError: expected rest argument name, got "x"
-SyntaxError: expected closing parenthesis, got "x"
-SyntaxError: expected '=>' after argument list, got "x"
-
- -

Error type

- -

{{jsxref("SyntaxError")}}

- -

What went wrong?

- -

A specific language construct was expected, but something else was provided. This might be a simple typo.

- -

Examples

- -

Expression expected

- -

For example, when chaining expressions, trailing commas are not allowed.

- -
for (let i = 0; i < 5,; ++i) {
-  console.log(i);
-}
-// SyntaxError: expected expression, got ')'
-
- -

Correct would be omitting the comma or adding another expression:

- -
for (let i = 0; i < 5; ++i) {
-  console.log(i);
-}
-
- -

Not enough brackets

- -

Sometimes, you leave out brackets around if statements:

- -
function round(n, upperBound, lowerBound){
-  if(n > upperBound) || (n < lowerBound){
-    throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);
-  }else if(n < ((upperBound + lowerBound)/2)){
-    return lowerBound;
-  }else{
-    return upperBound;
-  }
-} // SyntaxError: expected expression, got '||'
- -

The brackets may look correct at first, but note how the || is outside the brackets. Correct would be putting brackets around the ||:

- -
function round(n, upperBound, lowerBound){
-  if((n > upperBound) || (n < lowerBound)){
-    throw 'Number ' + String(n) + ' is more than ' + String(upperBound) + ' or less than ' + String(lowerBound);
-  }else if(n < ((upperBound + lowerBound)/2)){
-    return lowerBound;
-  }else{
-    return upperBound;
-  }
-}
-
- -

See also

- - diff --git a/files/fa/web/javascript/reference/functions/index.html b/files/fa/web/javascript/reference/functions/index.html deleted file mode 100644 index 4f1c4136cc..0000000000 --- a/files/fa/web/javascript/reference/functions/index.html +++ /dev/null @@ -1,596 +0,0 @@ ---- -title: Functions -slug: Web/JavaScript/Reference/Functions -tags: - - Constructor - - Function - - Functions - - JavaScript - - NeedsTranslation - - Parameter - - TopicStub - - parameters -translation_of: Web/JavaScript/Reference/Functions ---- -
{{jsSidebar("Functions")}}
- -

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

- -

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

- -

For more examples and explanations, see also the JavaScript guide about functions.

- -

Description

- -

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

- -

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

- -

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

- -
/* Declare the function 'myFunc' */
-function myFunc(theObject) {
-   theObject.brand = "Toyota";
- }
-
- /*
-  * Declare variable 'mycar';
-  * create and initialize a new Object;
-  * assign reference to it to 'mycar'
-  */
- var mycar = {
-   brand: "Honda",
-   model: "Accord",
-   year: 1998
- };
-
- /* Logs 'Honda' */
- console.log(mycar.brand);
-
- /* Pass object reference to the function */
- myFunc(mycar);
-
- /*
-  * Logs 'Toyota' as the value of the 'brand' property
-  * of the object, as changed to by the function.
-  */
- console.log(mycar.brand);
-
- -

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

- -

Defining functions

- -

There are several ways to define functions:

- -

The function declaration (function statement)

- -

There is a special syntax for declaring functions (see function statement for details):

- -
function name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The function expression (function expression)

- -

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

- -
function [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

Here is an example of an anonymous function expression (the name is not used):

- -
var myFunction = function() {
-    statements
-}
- -

It is also possible to provide a name inside the definition in order to create a named function expression:

- -
var myFunction = function namedFunction(){
-    statements
-}
-
- -

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

- -

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

- -

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

- -
(function() {
-    statements
-})();
- -

IIFE are function expressions that are invoked as soon as the function is declared.

- -

The generator function declaration (function* statement)

- -

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

- -
function* name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The generator function expression (function* expression)

- -

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

- -
function* [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

The arrow function expression (=>)

- -

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

- -
([param[, param]]) => {
-   statements
-}
-
-param => expression
-
- -
-
param
-
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
-
statements or expression
-
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
-
- -

The Function constructor

- -
-

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

- -
new Function (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function body.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

The GeneratorFunction constructor

- -
-

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

-
- -
-

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

- -
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Function parameters

- -

Default parameters

- -

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

- -

Rest parameters

- -

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

- -

The arguments object

- -

You can refer to a function's arguments within the function by using the arguments object. See arguments.

- - - -

Defining method functions

- -

Getter and setter functions

- -

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -
-
get
-
-

Binds an object property to a function that will be called when that property is looked up.

-
-
set
-
Binds an object property to a function to be called when there is an attempt to set that property.
-
- -

Method definition syntax

- -

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

- -
var obj = {
-  foo() {},
-  bar() {}
-};
- -

Function constructor vs. function declaration vs. function expression

- -

Compare the following:

- -

A function defined with the Function constructor assigned to the variable multiply:

- -
var multiply = new Function('x', 'y', 'return x * y');
- -

A function declaration of a function named multiply:

- -
function multiply(x, y) {
-   return x * y;
-} // there is no semicolon here
-
- -

A function expression of an anonymous function assigned to the variable multiply:

- -
var multiply = function(x, y) {
-   return x * y;
-};
-
- -

A function expression of a function named func_name assigned to the variable multiply:

- -
var multiply = function func_name(x, y) {
-   return x * y;
-};
-
- -

Differences

- -

All do approximately the same thing, with a few subtle differences:

- -

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

- -
var y = function x() {};
-alert(x); // throws an error
-
- -

The function name also appears when the function is serialized via Function's toString method.

- -

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

- -

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

- -

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

- -
function anonymous() {
-}
-
- -

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

- -
var foo = new Function("alert(anonymous);");
-foo();
-
- -

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

- -
foo(); // alerts FOO!
-function foo() {
-   alert('FOO!');
-}
-
- -

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

- -
/*
- * Declare and initialize a variable 'p' (global)
- * and a function 'myFunc' (to change the scope) inside which
- * declare a varible with same name 'p' (current) and
- * define three functions using three different ways:-
- *     1. function declaration
- *     2. function expression
- *     3. function constructor
- * each of which will log 'p'
- */
-var p = 5;
-function myFunc() {
-    var p = 9;
-
-    function decl() {
-        console.log(p);
-    }
-    var expr = function() {
-        console.log(p);
-    };
-    var cons = new Function('\tconsole.log(p);');
-
-    decl();
-    expr();
-    cons();
-}
-myFunc();
-
-/*
- * Logs:-
- * 9  - for 'decl' by function declaration (current scope)
- * 9  - for 'expr' by function expression (current scope)
- * 5  - for 'cons' by Function constructor (global scope)
- */
-
- -

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

- -

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

- -
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
-foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
- -

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

- - - -
var x = 0;               // source element
-if (x === 0) {           // source element
-   x = 10;               // not a source element
-   function boo() {}     // not a source element
-}
-function foo() {         // source element
-   var y = 20;           // source element
-   function bar() {}     // source element
-   while (y === 10) {    // source element
-      function blah() {} // not a source element
-      y++;               // not a source element
-   }
-}
-
- -

Examples

- -
// function declaration
-function foo() {}
-
-// function expression
-(function bar() {})
-
-// function expression
-x = function hello() {}
-
-
-if (x) {
-   // function expression
-   function world() {}
-}
-
-
-// function declaration
-function a() {
-   // function declaration
-   function b() {}
-   if (0) {
-      // function expression
-      function c() {}
-   }
-}
-
- -

Block-level functions

- -

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -
'use strict';
-
-function f() {
-  return 1;
-}
-
-{
-  function f() {
-    return 2;
-  }
-}
-
-f() === 1; // true
-
-// f() === 2 in non-strict mode
-
- -

Block-level functions in non-strict code

- -

In a word: Don't.

- -

In non-strict code, function declarations inside blocks behave strangely. For example:

- -
if (shouldDefineZero) {
-   function zero() {     // DANGER: compatibility risk
-      console.log("This is zero.");
-   }
-}
-
- -

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

- -

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

- -

A safer way to define functions conditionally is to assign a function expression to a variable:

- -
var zero;
-if (shouldDefineZero) {
-   zero = function() {
-      console.log("This is zero.");
-   };
-}
-
- -

Examples

- -

Returning a formatted number

- -

The following function returns a string containing the formatted representation of a number padded with leading zeros.

- -
// This function returns a string padded with leading zeros
-function padZeros(num, totalLen) {
-   var numStr = num.toString();             // Initialize return value as string
-   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
-   for (var i = 1; i <= numZeros; i++) {
-      numStr = "0" + numStr;
-   }
-   return numStr;
-}
-
- -

The following statements call the padZeros function.

- -
var result;
-result = padZeros(42,4); // returns "0042"
-result = padZeros(42,2); // returns "42"
-result = padZeros(5,4);  // returns "0005"
-
- -

Determining whether a function exists

- -

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

- -
 if ('function' === typeof window.noFunc) {
-   // use noFunc()
- } else {
-   // do something else
- }
-
- -

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.functions")}}

- -

See also

- - diff --git a/files/fa/web/javascript/reference/global_objects/array/index.html b/files/fa/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 8780c0cb7b..0000000000 --- a/files/fa/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,464 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - Example - - Global Objects - - JavaScript - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -
شیء Array در جاوااسکریپت یک شیء عمومی است که در ساخت آرایه ها استفاده می شود که اشیائی سطح بالا شبیه فهرست هستند.
- -
- -

ساخت یک آرایه

- -
var fruits = ['Apple', 'Banana'];
-
-console.log(fruits.length);
-// 2
-
- -

دسترسی به یک آیتم در آرایه (بر اساس نمایه)

- -
var first = fruits[0];
-// Apple
-
-var last = fruits[fruits.length - 1];
-// Banana
-
- -

اجرای حلقه روی آرایه

- -
fruits.forEach(function(item, index, array) {
-  console.log(item, index);
-});
-// Apple 0
-// Banana 1
-
- -

اضافه کردن به انتهای آرایه

- -
var newLength = fruits.push('Orange');
-// ["Apple", "Banana", "Orange"]
-
- -

حذف کردن از انتهای آرایه

- -
var last = fruits.pop(); // remove Orange (from the end)
-// ["Apple", "Banana"];
-
- -

حذف کردن از ابتدای آرایه

- -
var first = fruits.shift(); // remove Apple from the front
-// ["Banana"];
-
- -

اضافه کردن به ابتدای آرایه

- -
var newLength = fruits.unshift('Strawberry') // add to the front
-// ["Strawberry", "Banana"];
-
- -

پیدا کردن نمایه یک آیتم در یک آرایه

- -
fruits.push('Mango');
-// ["Strawberry", "Banana", "Mango"]
-
-var pos = fruits.indexOf('Banana');
-// 1
-
- -

پاک کردن یک آیتم بر اساس موقعیت نمایه

- -
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
-
-// ["Strawberry", "Mango"]
- -

پاک کردن آیتم ها بر اساس موقعیت نمایه

- -
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
-console.log(vegetables);
-// ["Cabbage", "Turnip", "Radish", "Carrot"]
-
-var pos = 1, n = 2;
-
-var removedItems = vegetables.splice(pos, n);
-// this is how to remove items, n defines the number of items to be removed,
-// from that position(pos) onward to the end of array.
-
-console.log(vegetables);
-// ["Cabbage", "Carrot"] (the original array is changed)
-
-console.log(removedItems);
-// ["Turnip", "Radish"]
- -

کپی کردن یک آرایه

- -
var shallowCopy = fruits.slice(); // this is how to make a copy
-// ["Strawberry", "Mango"]
-
- -

Syntax

- -
[element0, element1, ..., elementN]
-new Array(element0, element1[, ...[, elementN]])
-new Array(arrayLength)
- -

Parameters

- -
-
elementN
-
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below). Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
-
arrayLength
-
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
-
- -

Description

- -

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

- -

Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

- -

Accessing array elements

- -

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1. Using an invalid index number returns undefined.

- -
var arr = ['this is the first element', 'this is the second element', 'this is the last element'];
-console.log(arr[0]);              // logs 'this is the first element'
-console.log(arr[1]);              // logs 'this is the second element'
-console.log(arr[arr.length - 1]); // logs 'this is the last element'
-
- -

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error because the property name is not valid:

- -
console.log(arr.0); // a syntax error
-
- -

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0);   // a syntax error
-console.log(years[0]);  // works properly
-
- -
renderer.3d.setTexture(model, 'character.png');     // a syntax error
-renderer['3d'].setTexture(model, 'character.png');  // works properly
-
- -

Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is, for this reason, that '2' and '02' would refer to two different slots on the years object and the following example could be true:

- -
console.log(years['2'] != years['02']);
-
- -

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation (but it can be accessed by dot notation in firefox 40.0a2 at least):

- -
var promise = {
-  'var'  : 'text',
-  'array': [1, 2, 3, 4]
-};
-
-console.log(promise['var']);
-
- -

Relationship between length and numerical properties

- -

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join()")}}, {{jsxref("Array.slice", "slice()")}}, {{jsxref("Array.indexOf", "indexOf()")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push()")}}, {{jsxref("Array.splice", "splice()")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

- -
var fruits = [];
-fruits.push('banana', 'apple', 'peach');
-
-console.log(fruits.length); // 3
-
- -

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

- -
fruits[5] = 'mango';
-console.log(fruits[5]); // 'mango'
-console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
-console.log(fruits.length); // 6
-
- -

Increasing the {{jsxref("Array.length", "length")}}.

- -
fruits.length = 10;
-console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
-console.log(fruits.length); // 10
-
- -

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

- -
fruits.length = 2;
-console.log(Object.keys(fruits)); // ['0', '1']
-console.log(fruits.length); // 2
-
- -

This is explained further on the {{jsxref("Array.length")}} page.

- -

Creating an array using the result of a match

- -

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

- -
// Match one d followed by one or more b's followed by one d
-// Remember matched b's and the following d
-// Ignore case
-
-var myRe = /d(b+)(d)/i;
-var myArray = myRe.exec('cdbBdbsbz');
-
- -

The properties and elements returned from this match are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
- [2]: d
- -

Properties

- -
-
Array.length
-
The Array constructor's length property whose value is 1.
-
{{jsxref("Array.@@species", "get Array[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Array.prototype")}}
-
Allows the addition of properties to all array objects.
-
- -

Methods

- -
-
{{jsxref("Array.from()")}}
-
Creates a new Array instance from an array-like or iterable object.
-
{{jsxref("Array.isArray()")}}
-
Returns true if a variable is an array, if not false.
-
{{jsxref("Array.of()")}}
-
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
-
- -

Array instances

- -

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
- -

Methods

- -

Mutator methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
- -

Accessor methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
- -

Iteration methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
- -

Array generic methods

- -
-

Array generics are non-standard, deprecated and will get removed in the near future.

-
- -

{{Obsolete_Header("Gecko71")}}

- -

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

- -
function isLetter(character) {
-  return character >= 'a' && character <= 'z';
-}
-
-if (Array.prototype.every.call(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

- -
if (Array.every(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

- -

These are not part of ECMAScript standards and they are not supported by non-Gecko browsers. As a standard alternative, you can convert your object to a proper array using {{jsxref("Array.from()")}}; although that method may not be supported in old browsers:

- -
if (Array.from(str).every(isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

Examples

- -

Creating an array

- -

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

- -
var msgArray = [];
-msgArray[0] = 'Hello';
-msgArray[99] = 'world';
-
-if (msgArray.length === 100) {
-  console.log('The length is 100.');
-}
-
- -

Creating a two-dimensional array

- -

The following creates a chess board as a two-dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

- -
var board = [
-  ['R','N','B','Q','K','B','N','R'],
-  ['P','P','P','P','P','P','P','P'],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  ['p','p','p','p','p','p','p','p'],
-  ['r','n','b','q','k','b','n','r'] ];
-
-console.log(board.join('\n') + '\n\n');
-
-// Move King's Pawn forward 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-console.log(board.join('\n'));
-
- -

Here is the output:

- -
R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
-p,p,p,p,p,p,p,p
-r,n,b,q,k,b,n,r
-
-R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , ,p, , ,
- , , , , , , ,
-p,p,p,p, ,p,p,p
-r,n,b,q,k,b,n,r
-
- -

Using an array to tabulate a set of values

- -
values = [];
-for (var x = 0; x < 10; x++){
- values.push([
-  2 ** x,
-  2 * x ** 2
- ])
-};
-console.table(values)
- -

Results in

- -
0	1	0
-1	2	2
-2	4	8
-3	8	18
-4	16	32
-5	32	50
-6	64	72
-7	128	98
-8	256	128
-9	512	162
- -

(First column is the (index))

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ES7', '#sec-array-objects', 'Array')}}{{Spec2('ES7')}}New method added: {{jsxref("Array.prototype.includes()")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- - - -

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

- -

See also

- - diff --git a/files/fa/web/javascript/reference/global_objects/array/of/index.html b/files/fa/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index 0c5aa6d2fa..0000000000 --- a/files/fa/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -
متد Array.of() یک آرایه ی جدید شامل آرگومان های ارسال شده به آن میباشد میسازد، صرفنظر از تعداد و نوع آرگومان ها. 
- -

تفاوت متد  Array.of() و متد سازنده ی  Array() در این میباشد که  Array.of(7) یک آرایه با یک المنت که مقدارش 7 میباشد میسازد. در حالیکه Array(7) یک آرایه ی جدید با طول 7 که شامل 7 المنت یا slot با مقدار empty میسازد نه با مقدار  undefined.

- -
Array.of(7);       // [7]
-Array.of(1, 2, 3); // [1, 2, 3]
-
-Array(7);          // array of 7 empty slots
-Array(1, 2, 3);    // [1, 2, 3]
-
- -

نحوه استفاده

- -
Array.of(element0[, element1[, ...[, elementN]]])
- -

پارامترها

- -
-
elementN
-
لیست المنت هایی که باید درون آرایه قرار بگیرند.
-
- -

مقدار بازگشتی

- -

یک نمونه جدید از {{jsxref("Array")}} .

- -

توضیحات

- -

این تابع بخشی از ECMAScript 2015 استاندارد است. برای اطلاعات بیشتر لینک های زیر مراجعه کنید:

- -

Array.of و Array.from proposal و Array.of polyfill.

- -

مثال

- -
Array.of(1);         // [1]
-Array.of(1, 2, 3);   // [1, 2, 3]
-Array.of(undefined); // [undefined]
-
- -

چند کاره سازی

- -

در صورت عدم وجود Array.of() به صورت پیشفرض، با اجرای کد زیر قبل اجرای سایر کدها، تابع  Array.of() را برای شما در کلاس Array پیاده سازی و قابل استفاده می نماید. برید حالشو ببرید.

- -
if (!Array.of) {
-  Array.of = function() {
-    return Array.prototype.slice.call(arguments);
-    // Or
-    let vals = [];
-    for(let prop in arguments){
-        vals.push(arguments[prop]);
-    }
-    return vals;
-  }
-}
-
- -

مشخصه ها

- - - - - - - - - - - - - - - - - - - - - -
مشخصهوضعیتتوضیح
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Initial definition.
- -

سازگاری با سایر مرورگرها

- -
- - -

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

-
- -

همچنین ببینید

- - diff --git a/files/fa/web/javascript/reference/global_objects/array/reduce/index.html b/files/fa/web/javascript/reference/global_objects/array/reduce/index.html deleted file mode 100644 index 6145fa772e..0000000000 --- a/files/fa/web/javascript/reference/global_objects/array/reduce/index.html +++ /dev/null @@ -1,579 +0,0 @@ ---- -title: Array.prototype.reduce() -slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce -translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce ---- -
{{JSRef}}
- -

 The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

- -

متد reduce یک تابع reducer (کاهش دهنده) را بر روی هر کدام از المان‌های آرایه اجرا می‌کند و در خروجی یک آرایه برمی‌گرداند. توجه داشته باشید که تابع reducer را شما باید بنویسید.

- -
{{EmbedInteractiveExample("pages/js/array-reduce.html")}}
- - - -

یک تابع کاهش دهنده 4 آرگومان دریافت می‌کند

- -

The reducer function takes four arguments:

- -
    -
  1. Accumulator (acc) (انباشت کننده)
  2. -
  3. Current Value (cur) (مقدار فعلی)
  4. -
  5. Current Index (idx) (اندیس فعلی)
  6. -
  7. Source Array (src) (آرایه‌ی مبدا)
  8. -
- -

Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.

- -

بنابراین آرگومان اول تابع reduce، کاهش دهنده، و آرگومان دوم، انباشتگر می‌باشد. به این ترتیب پس از اعمال کاهش دهنده بر روی هر کدام از المان‌های آرایه، انباشت کننده یا اکیومیولیتور نیز اعمال اثر می‌کند.

- -

Syntax

- -
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
- -

Parameters

- -
-
callback
-
A function to execute on each element in the array (except for the first, if no initialValue is supplied), taking four arguments: -
-
accumulator
-
The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).
-
currentValue
-
The current element being processed in the array.
-
index {{optional_inline}}
-
The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, starts from index 1.
-
array {{optional_inline}}
-
The array reduce() was called upon.
-
-
-
initialValue {{optional_inline}}
-
A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used and skipped. Calling reduce() on an empty array without an initialValue will throw a TypeError.
-
- -

Return value

- -

The single value that results from the reduction.

- -

مقدار بازگشتی مقداری واحد است.

- -

Description

- -

The reduce() method executes the callback once for each assigned value present in the array, taking four arguments:

- -

تابع reduce، کال بک را یک بار بر روی مقدارهای الصاق شده در ارایه اعمال می کند و چهار ارگومان (ورودی) زیر را می پذیرد.

- - - -

The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

- -
-

Note: If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

-
- -

If the array is empty and no initialValue is provided, {{jsxref("TypeError")}} will be thrown. If the array only has one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned without calling callback.

- -

It is usually safer to provide an initialValue because there are three possible outputs without initialValue, as shown in the following example.

- -

برای احتیاط بهتر است که همیشه یک initialValue یا مقدار اولیه درنظر گرفت زیرا در صورت در نظر نگرفتن مقدار اولیه سه حالت ممکن است رخ دهد که در مثال زیر توضیح داده شده است.

- -
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
-var maxCallback2 = ( max, cur ) => Math.max( max, cur );
-
-// reduce() without initialValue
-[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
-[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
-[                      ].reduce( maxCallback ); // TypeError
-
-// map/reduce; better solution, also works for empty or larger arrays
-[ { x: 22 }, { x: 42 } ].map( el => el.x )
-                        .reduce( maxCallback2, -Infinity );
-
- -

How reduce() works

- -

Suppose the following use of reduce() occurred:

- -
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
-  return accumulator + currentValue;
-});
-
- -

The callback would be invoked four times, with the arguments and return values in each call being as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call011[0, 1, 2, 3, 4]1
second call122[0, 1, 2, 3, 4]3
third call333[0, 1, 2, 3, 4]6
fourth call644[0, 1, 2, 3, 4]10
- -

The value returned by reduce() would be that of the last callback invocation (10).

- -

You can also provide an {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} instead of a full function. The code below will produce the same output as the code in the block above:

- -
[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue );
-
- -

If you were to provide an initialValue as the second argument to reduce(), the result would look like this:

- -
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
-    return accumulator + currentValue;
-}, 10);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call1000[0, 1, 2, 3, 4]10
second call1011[0, 1, 2, 3, 4]11
third call1122[0, 1, 2, 3, 4]13
fourth call1333[0, 1, 2, 3, 4]16
fifth call1644[0, 1, 2, 3, 4]20
- -

The value returned by reduce() in this case would be 20.

- -

Examples

- -

Sum all the values of an array

- -
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
-  return accumulator + currentValue;
-}, 0);
-// sum is 6
-
-
- -

Alternatively written with an arrow function:

- -
var total = [ 0, 1, 2, 3 ].reduce(
-  ( accumulator, currentValue ) => accumulator + currentValue,
-  0
-);
- -

Sum of values in an object array

- -

To sum up the values contained in an array of objects, you must supply an initialValue, so that each item passes through your function.

- -
var initialValue = 0;
-var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) {
-    return accumulator + currentValue.x;
-},initialValue)
-
-console.log(sum) // logs 6
-
- -

Alternatively written with an arrow function:

- -
var initialValue = 0;
-var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
-    (accumulator, currentValue) => accumulator + currentValue.x
-    ,initialValue
-);
-
-console.log(sum) // logs 6
- -

Flatten an array of arrays

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  function(accumulator, currentValue) {
-    return accumulator.concat(currentValue);
-  },
-  []
-);
-// flattened is [0, 1, 2, 3, 4, 5]
-
- -

Alternatively written with an arrow function:

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  ( accumulator, currentValue ) => accumulator.concat(currentValue),
-  []
-);
-
- -

Counting instances of values in an object

- -
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
-
-var countedNames = names.reduce(function (allNames, name) {
-  if (name in allNames) {
-    allNames[name]++;
-  }
-  else {
-    allNames[name] = 1;
-  }
-  return allNames;
-}, {});
-// countedNames is:
-// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
-
- -

Grouping objects by a property

- -
var people = [
-  { name: 'Alice', age: 21 },
-  { name: 'Max', age: 20 },
-  { name: 'Jane', age: 20 }
-];
-
-function groupBy(objectArray, property) {
-  return objectArray.reduce(function (acc, obj) {
-    var key = obj[property];
-    if (!acc[key]) {
-      acc[key] = [];
-    }
-    acc[key].push(obj);
-    return acc;
-  }, {});
-}
-
-var groupedPeople = groupBy(people, 'age');
-// groupedPeople is:
-// {
-//   20: [
-//     { name: 'Max', age: 20 },
-//     { name: 'Jane', age: 20 }
-//   ],
-//   21: [{ name: 'Alice', age: 21 }]
-// }
-
- -

Bonding arrays contained in an array of objects using the spread operator and initialValue

- -
// friends - an array of objects
-// where object field "books" - list of favorite books
-var friends = [{
-  name: 'Anna',
-  books: ['Bible', 'Harry Potter'],
-  age: 21
-}, {
-  name: 'Bob',
-  books: ['War and peace', 'Romeo and Juliet'],
-  age: 26
-}, {
-  name: 'Alice',
-  books: ['The Lord of the Rings', 'The Shining'],
-  age: 18
-}];
-
-// allbooks - list which will contain all friends' books +
-// additional list contained in initialValue
-var allbooks = friends.reduce(function(accumulator, currentValue) {
-  return [...accumulator, ...currentValue.books];
-}, ['Alphabet']);
-
-// allbooks = [
-//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
-//   'Romeo and Juliet', 'The Lord of the Rings',
-//   'The Shining'
-// ]
- -

Remove duplicate items in array

- -
-

Note: If you are using an environment compatible with {{jsxref("Set")}} and {{jsxref("Array.from()")}}, you could use let orderedArray = Array.from(new Set(myArray)); to get an array where duplicate items have been removed.

-
- -
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
-var myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
-  if (accumulator.indexOf(currentValue) === -1) {
-    accumulator.push(currentValue);
-  }
-  return accumulator
-}, [])
-
-console.log(myOrderedArray);
- -

Running Promises in Sequence

- -
/**
- * Runs promises from array of functions that can return promises
- * in chained manner
- *
- * @param {array} arr - promise arr
- * @return {Object} promise object
- */
-function runPromiseInSequence(arr, input) {
-  return arr.reduce(
-    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
-    Promise.resolve(input)
-  );
-}
-
-// promise function 1
-function p1(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 5);
-  });
-}
-
-// promise function 2
-function p2(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 2);
-  });
-}
-
-// function 3  - will be wrapped in a resolved promise by .then()
-function f3(a) {
- return a * 3;
-}
-
-// promise function 4
-function p4(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 4);
-  });
-}
-
-const promiseArr = [p1, p2, f3, p4];
-runPromiseInSequence(promiseArr, 10)
-  .then(console.log);   // 1200
-
- -

Function composition enabling piping

- -
// Building-blocks to use for composition
-const double = x => x + x;
-const triple = x => 3 * x;
-const quadruple = x => 4 * x;
-
-// Function composition enabling pipe functionality
-const pipe = (...functions) => input => functions.reduce(
-    (acc, fn) => fn(acc),
-    input
-);
-
-// Composed functions for multiplication of specific values
-const multiply6 = pipe(double, triple);
-const multiply9 = pipe(triple, triple);
-const multiply16 = pipe(quadruple, quadruple);
-const multiply24 = pipe(double, triple, quadruple);
-
-// Usage
-multiply6(6); // 36
-multiply9(9); // 81
-multiply16(16); // 256
-multiply24(10); // 240
-
-
- -

write map using reduce

- -
if (!Array.prototype.mapUsingReduce) {
-  Array.prototype.mapUsingReduce = function(callback, thisArg) {
-    return this.reduce(function(mappedArray, currentValue, index, array) {
-      mappedArray[index] = callback.call(thisArg, currentValue, index, array);
-      return mappedArray;
-    }, []);
-  };
-}
-
-[1, 2, , 3].mapUsingReduce(
-  (currentValue, index, array) => currentValue + index + array.length
-); // [5, 7, , 10]
-
-
- -

Polyfill

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.21
-// Reference: http://es5.github.io/#x15.4.4.21
-// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
-if (!Array.prototype.reduce) {
-  Object.defineProperty(Array.prototype, 'reduce', {
-    value: function(callback /*, initialValue*/) {
-      if (this === null) {
-        throw new TypeError( 'Array.prototype.reduce ' +
-          'called on null or undefined' );
-      }
-      if (typeof callback !== 'function') {
-        throw new TypeError( callback +
-          ' is not a function');
-      }
-
-      // 1. Let O be ? ToObject(this value).
-      var o = Object(this);
-
-      // 2. Let len be ? ToLength(? Get(O, "length")).
-      var len = o.length >>> 0;
-
-      // Steps 3, 4, 5, 6, 7
-      var k = 0;
-      var value;
-
-      if (arguments.length >= 2) {
-        value = arguments[1];
-      } else {
-        while (k < len && !(k in o)) {
-          k++;
-        }
-
-        // 3. If len is 0 and initialValue is not present,
-        //    throw a TypeError exception.
-        if (k >= len) {
-          throw new TypeError( 'Reduce of empty array ' +
-            'with no initial value' );
-        }
-        value = o[k++];
-      }
-
-      // 8. Repeat, while k < len
-      while (k < len) {
-        // a. Let Pk be ! ToString(k).
-        // b. Let kPresent be ? HasProperty(O, Pk).
-        // c. If kPresent is true, then
-        //    i.  Let kValue be ? Get(O, Pk).
-        //    ii. Let accumulator be ? Call(
-        //          callbackfn, undefined,
-        //          « accumulator, kValue, k, O »).
-        if (k in o) {
-          value = callback(value, o[k], k, o);
-        }
-
-        // d. Increase k by 1.
-        k++;
-      }
-
-      // 9. Return accumulator.
-      return value;
-    }
-  });
-}
-
- -

If you need to support truly obsolete JavaScript engines that do not support Object.defineProperty(), it is best not to polyfill Array.prototype methods at all, as you cannot make them non-enumerable.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/fa/web/javascript/reference/global_objects/function/index.html b/files/fa/web/javascript/reference/global_objects/function/index.html deleted file mode 100644 index 4c80478bda..0000000000 --- a/files/fa/web/javascript/reference/global_objects/function/index.html +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Function -slug: Web/JavaScript/Reference/Global_Objects/Function -tags: - - Constructor - - Function - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Function ---- -
{{JSRef}}
- -

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues to {{jsxref("eval")}}. However, unlike eval, the Function constructor creates functions which execute in the global scope only.

- -
{{EmbedInteractiveExample("pages/js/function-constructor.html")}}
- - - -

Every JavaScript function is actually a Function object. This can be seen with the code (function(){}).constructor === Function which returns true.

- -

Syntax

- -
new Function ([arg1[, arg2[, ...argN]],] functionBody)
- -

Parameters

- -
-
arg1, arg2, ... argN
-
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Description

- -

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code because such functions are parsed with the rest of the code.

- -

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. Omitting an argument will result in the value of that parameter being undefined.

- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Properties and Methods of Function

- -

The global Function object has no methods or properties of its own. However, since it is a function itself, it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

- -

Function prototype object

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
- -

Methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
- -

Function instances

- -

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

- -

Examples

- -

Specifying arguments with the Function constructor

- -

The following code creates a Function object that takes two arguments.

- -
// Example can be run directly in your JavaScript console
-
-// Create a function that takes two arguments and returns the sum of those arguments
-var adder = new Function('a', 'b', 'return a + b');
-
-// Call the function
-adder(2, 6);
-// > 8
-
- -

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

- -

Difference between Function constructor and function declaration

- -

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created. This is different from using {{jsxref("eval")}} with code for a function expression.

- -
var x = 10;
-
-function createFunction1() {
-    var x = 20;
-    return new Function('return x;'); // this |x| refers global |x|
-}
-
-function createFunction2() {
-    var x = 20;
-    function f() {
-        return x; // this |x| refers local |x| above
-    }
-    return f;
-}
-
-var f1 = createFunction1();
-console.log(f1());          // 10
-var f2 = createFunction2();
-console.log(f2());          // 20
-
- -

While this code works in web browsers, f1() will produce a ReferenceError in Node.js, as x will not be found. This is because the top-level scope in Node is not the global scope, and x will be local to the module.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/fa/web/javascript/reference/global_objects/index.html b/files/fa/web/javascript/reference/global_objects/index.html deleted file mode 100644 index 4db59a377c..0000000000 --- a/files/fa/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: Standard built-in objects -slug: Web/JavaScript/Reference/Global_Objects -tags: - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects ---- -
-
- {{jsSidebar("Objects")}}
-
-

Summary

-

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

-
-

The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, global objects refer to objects in the global scope (but only if ECMAScript 5 strict mode is not used! Otherwise it returns undefined). The global object itself can be accessed by the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope consists of the properties of the global object (including inherited properties, if any).

-

Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview.

-

Standard objects (by category)

-

Value properties

-

Global properties returning a simple value.

- -

Function properties

-

Global functions returning the result of a specific routine.

- -

Fundamental objects

-

General language objects, functions and errors.

- -

Numbers and dates

-

Objects dealing with numbers, dates and mathematical calculations.

- -

Text processing

-

Objects for manipulating texts.

- -

Indexed collections

-

Collections ordered by an index. Array-type objects.

- -

Keyed collections

-

Collections of objects as keys. Elements iterable in insertion order.

- -

Structured data

-

Data buffers and JavaScript Object Notation.

- -

Control abstraction objects

- -

Reflection

- -

Internationalization

-

Additions to the ECMAScript core for language-sensitive functionalities.

- -

Other

- -
-

 

diff --git a/files/fa/web/javascript/reference/global_objects/null/index.html b/files/fa/web/javascript/reference/global_objects/null/index.html deleted file mode 100644 index b90e55a245..0000000000 --- a/files/fa/web/javascript/reference/global_objects/null/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: 'null' -slug: Web/JavaScript/Reference/Global_Objects/null -translation_of: Web/JavaScript/Reference/Global_Objects/null ---- -
 
- -

مقدار null نمایان گر مقداری هست که به صورت دستی (عمدی) می توانیم به یک متغییر نسبت دهیم،null یکی از  {{Glossary("Primitive", "نوع های اولیه")}}. جاوا اسکریپت می باشد.

- -

شیوه ی نوشتن

- -
null
- -

توضیح

- -

null باید به صورت حروف کوچک نوشته شود،null اقلب برای مشخص کردن مکان object به کار برده می شود و به هیچ object وابسته نمی باشد

- -

زمانی که می خواهید مقدار null یا undefined  را بررسی کنید به تفاوت مابین عملگر های بررسی (==) و (===) اگاه باشید.

- -
// foo does not exist. It is not defined and has never been initialized:
-> foo
-"ReferenceError: foo is not defined"
-
-// foo is known to exist now but it has no type or value:
-> var foo = null; foo
-"null"
-
- -

تفاوت بین null  و undefined

- -
typeof null        // object (bug in ECMAScript, should be null)
-typeof undefined   // undefined
-null === undefined // false
-null  == undefined // true
-
- -

مشخصات

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
مشخصاتوضعیتتوضیحات
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-4.3.11', 'null value')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-null-value', 'null value')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-null-value', 'null value')}}{{Spec2('ESDraft')}} 
- -

سازگاری مرورگرها

- -

{{CompatibilityTable}}

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

بیشتر بخوانید

- - diff --git a/files/fa/web/javascript/reference/global_objects/regexp/index.html b/files/fa/web/javascript/reference/global_objects/regexp/index.html deleted file mode 100644 index 3419d5977b..0000000000 --- a/files/fa/web/javascript/reference/global_objects/regexp/index.html +++ /dev/null @@ -1,597 +0,0 @@ ---- -title: RegExp -slug: Web/JavaScript/Reference/Global_Objects/RegExp -tags: - - Constructor - - JavaScript - - NeedsTranslation - - RegExp - - Regular Expressions - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp ---- -
{{JSRef("Global_Objects", "RegExp")}}
- -

Summary

- -

The RegExp constructor creates a regular expression object for matching text with a pattern.

- -

For an introduction on what  regular expressions are, read the Regular Expressions chapter in the JavaScript Guide.

- -

Constructor

- -

Literal and constructor notations are possible:

- -
/pattern/flags;
-
-new RegExp(pattern [, flags]);
-
- -

Parameters

- -
-
pattern
-
The text of the regular expression.
-
flags
-
-

If specified, flags can have any combination of the following values:

- -
-
g
-
global match
-
i
-
ignore case
-
m
-
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
-
y
-
sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).
-
-
-
- -

Description

- -

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

- -
/ab+c/i;
-new RegExp("ab+c", "i");
-
- -

The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

- -

The constructor of the regular expression object, for example, new RegExp("ab+c"), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

- -

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

- -
var re = /\w+/;
-var re = new RegExp("\\w+");
-
- -

Special characters meaning in regular expressions

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Character Classes
CharacterMeaning
. -

(The dot, the decimal point) matches any single character except the newline characters: \n \r \u2028 or \u2029.

- -

Note that the m multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines the character set [^] can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.

- -

For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".

-
\d -

Matches a digit character in the basic Latin alphabet. Equivalent to [0-9].

- -

For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."

-
\D -

Matches any character that is not a digit in the basic Latin alphabet. Equivalent to [^0-9].

- -

For example, /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite number."

-
\w -

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_].

- -

For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."

-
\W -

Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].

- -

For example, /\W/ or /[^A-Za-z0-9_]/ matches '%' in "50%."

-
\s -

Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to [ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​ \u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​​\u202f\u205f​ \u3000].

- -

For example, /\s\w*/ matches ' bar' in "foo bar."

-
\S -

Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​ \u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u202f\u205f​\u3000].

- -

For example, /\S\w*/ matches 'foo' in "foo bar."

-
\tMatches a tab.
\rMatches a carriage return.
\nMatches a linefeed.
\vMatches a vertical tab.
\fMatches a form-feed.
[\b]Matches a backspace. (Not to be confused with \b)
\0Matches a NUL character. Do not follow this with another digit.
\cX -

Where X is a letter from A - Z. Matches a control character in a string.

- -

For example, /\cM/ matches control-M in a string.

-
\xhhMatches the character with the code hh (two hexadecimal digits)
\uhhhhMatches the character with the Unicode value hhhh (four hexadecimal digits).
\ -

For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.

- -

For example, /b/ matches the character 'b'. By placing a backslash in front of b, that is by using /\b/, the character becomes special to mean match a word boundary.

- -

or

- -

For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.

- -

For example, * is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more "a"s. To match * literally, precede it with a backslash; for example, /a\*/ matches 'a*'.

-
-

Character Sets

-
CharacterMeaning
[xyz] -

A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen.

- -

For example, [abcd] is the same as [a-d]. They match the 'b' in "brisket" and the 'c' in "chop".

-
[^xyz] -

A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen.

- -

For example, [^abc] is the same as [^a-c]. They initially match 'o' in "bacon" and 'h' in "chop."

-
Boundaries
CharacterMeaning
^ -

Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.

- -

For example, /^A/ does not match the 'A' in "an A", but does match the first 'A' in "An A."

-
$ -

Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.

- -

For example, /t$/ does not match the 't' in "eater", but does match it in "eat".

-
\b -

Matches a zero-width word boundary, such as between a letter and a space. (Not to be confused with [\b])

- -

For example, /\bno/ matches the 'no' in "at noon"; /ly\b/ matches the 'ly' in "possibly yesterday."

-
\B -

Matches a zero-width non-word boundary, such as between two letters or between two spaces.

- -

For example, /\Bon/ matches 'on' in "at noon", and /ye\B/ matches 'ye' in "possibly yesterday."

-
Grouping and back references
CharacterMeaning
(x) -

Matches x and remembers the match. These are called capturing parentheses.

- -

For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

- -

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).

-
\n -

Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

- -

For example, /apple(,)\sorange\1/ matches 'apple, orange,' in "apple, orange, cherry, peach." A more complete example follows this table.

-
(?:x)Matches x but does not remember the match. These are called non-capturing parentheses. The matched substring can not be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
Quantifiers
CharacterMeaning
x* -

Matches the preceding item x 0 or more times.

- -

For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled", but nothing in "A goat grunted".

-
x+ -

Matches the preceding item x 1 or more times. Equivalent to {1,}.

- -

For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy".

-
x*?
- x+?
-

Matches the preceding item x like * and + from above, however the match is the smallest possible match.

- -

For example, /".*?"/ matches '"foo"' in '"foo" "bar"' and does not match '"foo" "bar"' as without the ? behind the *.

-
x? -

Matches the preceding item x 0 or 1 time.

- -

For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle."

- -

If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).

- -

Also used in lookahead assertions, described under (?=), (?!), and (?:) in this table.

-
x(?=y)Matches x only if x is followed by y. For example, /Jack(?=Sprat)/ matches 'Jack' only if it is followed by 'Sprat'. /Jack(?=Sprat|Frost)/ matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.
x(?!y) -

Matches x only if x is not followed by y. For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point.

- -

/\d+(?!\.)/.exec("3.141") matches 141 but not 3.141.

-
x|y -

Matches either x or y.

- -

For example, /green|red/ matches 'green' in "green apple" and 'red' in "red apple."

-
x{n} -

Where n is a positive integer. Matches exactly n occurrences of the preceding item x.

- -

For example, /a{2}/ doesn't match the 'a' in "candy," but it matches all of the a's in "caandy," and the first two a's in "caaandy."

-
x{n,} -

Where n is a positive integer. Matches at least n occurrences of the preceding item x.

- -

For example, /a{2,}/ doesn't match the 'a' in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy."

-
x{n,m} -

Where n and m are positive integers. Matches at least n and at most m occurrences of the preceding item x.

- -

For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy," the two a's in "caandy," and the first three a's in "caaaaaaandy". Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more a's in it.

-
- -

Properties

- -
-
{{jsxref("RegExp.prototype")}}
-
Allows the addition of properties to all objects.
-
RegExp.length
-
The value of RegExp.length is 2.
-
- -
{{jsOverrides("Function", "Properties", "prototype")}}
- -

Methods

- -

The global RegExp object has no methods of its own, however, it does inherit some methods through the prototype chain.

- -
{{jsOverrides("Function", "Methods", "prototype")}}
- -

RegExp prototype objects and instances

- -

Properties

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype','Properties')}}
- -

Methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype','Methods')}}
- -

Examples

- -

Example: Using a regular expression to change data format

- -

The following script uses the {{jsxref("String.replace", "replace")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

- -
var re = /(\w+)\s(\w+)/;
-var str = "John Smith";
-var newstr = str.replace(re, "$2, $1");
-console.log(newstr);
- -

This displays "Smith, John".

- -

Example: Using regular expression on multiple lines

- -
var s = "Please yes\nmake my day!";
-s.match(/yes.*day/);
-// Returns null
-s.match(/yes[^]*day/);
-// Returns 'yes\nmake my day'
-
- -

Example: Using a regular expression with the "sticky" flag

- -

This example demonstrates how one could use the sticky flag on regular expressions to match individual lines of multiline input.

- -
var text = "First line\nSecond line";
-var regex = /(\S+) line\n?/y;
-
-var match = regex.exec(text);
-console.log(match[1]);  // prints "First"
-console.log(regex.lastIndex); // prints 11
-
-var match2 = regex.exec(text);
-console.log(match2[1]); // prints "Second"
-console.log(regex.lastIndex); // prints "22"
-
-var match3 = regex.exec(text);
-console.log(match3 === null); // prints "true"
- -

One can test at run-time whether the sticky flag is supported, using try { … } catch { … }. For this, either an eval(…) expression or the RegExp(regex-string, flags-string) syntax must be used (since the /regex/flags notation is processed at compile-time, so throws an exception before the catch block is encountered). For example:

- -
var supports_sticky;
-try { RegExp('','y'); supports_sticky = true; }
-catch(e) { supports_sticky = false; }
-alert(supports_sticky); // alerts "true"
- -

Example: Regular expression and Unicode characters

- -

As mentioned above, \w or \W only matches ASCII based characters; for example, 'a' to 'z', 'A' to 'Z', 0 to 9 and '_'. To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh., where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.

- -
var text = "Образец text на русском языке";
-var regex = /[\u0400-\u04FF]+/g;
-
-var match = regex.exec(text);
-console.log(match[0]);  // prints "Образец"
-console.log(regex.lastIndex);  // prints "7"
-
-var match2 = regex.exec(text);
-console.log(match2[0]);  // prints "на" [did not print "text"]
-console.log(regex.lastIndex);  // prints "15"
-
-// and so on
- -

Here's an external resource for getting the complete Unicode block range for different scripts: Regexp-unicode-block

- -

Example: Extracting subdomain name from URL

- -
var url = "http://xxx.domain.com";
-console.log(/[^.]+/.exec(url)[0].substr(7)); // prints "xxx"
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition. Implemented in JavaScript 1.1StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ES6')}} 
- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Sticky flag ("y")39 (behind flag){{ CompatGeckoDesktop("1.9") }} ES4-Style {{bug(773687)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Sticky flag ("y"){{ CompatNo() }}{{ CompatNo() }}{{ CompatGeckoDesktop("1.9") }} ES4-Style {{bug(773687)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -

See also

- - diff --git a/files/fa/web/javascript/reference/global_objects/regexp/test/index.html b/files/fa/web/javascript/reference/global_objects/regexp/test/index.html deleted file mode 100644 index 1690ceb375..0000000000 --- a/files/fa/web/javascript/reference/global_objects/regexp/test/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: RegExp.prototype.test() -slug: Web/JavaScript/Reference/Global_Objects/RegExp/test -tags: - - جاوا اسکریپت - - جستجو - - متد -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/test ---- -
- {{JSRef("Global_Objects", "RegExp")}}
-

خلاصه

-

متد test یک جستجو برای یافتن رشته خاص در متن یا رشته مورد نظر انجام میدهد و True یا False برمیگرداند.

-

ساختار

-
regexObj.test(str)
-

پارامتر ها

-
-
- str
-
- رشته ای که میخواهید با متن مورد نظر تطابق دهید.
-
-

مقدار بازگشتی

-

مقدار بازگشتی از نوع Boolean بوده و True یا False میباشد.

-

توضیحات

-

متد test() زمانی استفاده میشود که میخواهید الگو مورد نظر خود را در یک متن جستجو کنید و از وجود آن در متن مورد نظر با خبر شوید.

-

متدهای مرتبط : {jsxref("String.search") , {jsxref("RegExp.exec", "exec")

-

مثال

-

مثال: استفاده از test

-

مثال زیر یک خروجی را چاپ میکند که اشاره به موفقیت آمیز بودن جستجو دارد:

-
function testinput(re, str){
-    var midstring;
-    if (re.test(str)) {
-        midstring = " contains ";
-    } else {
-        midstring = " does not contain ";
-    }
-    console.log(str + midstring + re.source);
-}
-
-

خصوصیات

- - - - - - - - - - - - - - - - - - - - - - - -
خصوصیتوضعیتیاداشت
ECMAScript 3rd Edition. Implemented in JavaScript 1.2StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.10.6.3', 'RegExp.test')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp.prototype.test', 'RegExp.test')}}{{Spec2('ES6')}} 
-

سازگاری با مرورگرها

-

{{ CompatibilityTable() }}

-
- - - - - - - - - - - - - - - - - - - -
خصوصیاتگوگل کرومفایرفاکساینترنت اکسپلورراپراسافاری
پشتیبانی ابتدایی{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
-
- - - - - - - - - - - - - - - - - - - - - -
خصوصیاتاندرویدگوگل کروم برای اندرویدفایرفاکس موبایلاینترنت اکسپلورر موبایلاپرا موبایلسافاری موبایل
پشتیبانی ابتدایی{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
-

 

-

یادداشتی برای Gecko-specific

-

قبل از نسخه Gecko 8.0 {{ geckoRelease("8.0") }} تابع test() مشکلاتی به همراه داشت ، زمانی که این تابع بدون پارامتر ورودی فراخوانی میشد الگو را با متن قبلی مطابقت میداد (RegExp.input property) در حالی که بایستی رشته "undefined" را قرار میداد. در حال حاضر این مشکل برطرف شده است و این تابع به درستی کار میکند.

-

 

-

 

-

همچنین سری بزنید به :

- diff --git a/files/fa/web/javascript/reference/global_objects/set/index.html b/files/fa/web/javascript/reference/global_objects/set/index.html deleted file mode 100644 index c756b38195..0000000000 --- a/files/fa/web/javascript/reference/global_objects/set/index.html +++ /dev/null @@ -1,459 +0,0 @@ ---- -title: مجموعه | Set -slug: Web/JavaScript/Reference/Global_Objects/Set -tags: - - جاوااسکریپت - - مجموعه -translation_of: Web/JavaScript/Reference/Global_Objects/Set ---- -
-
{{JSRef}}
- -
شیء Set به شما اجازه می‌دهد مجموعه‌ای از مقادیر منحصر به فرد را از هر نوعی که باشند ذخیره کنید، چه {{Glossary("Primitive", "مقادیر اوّلیّه (Primitive)")}} باشند، چه ارجاع‌هایی به اشیاء.
- -

Syntax

- -
new Set([iterable]);
- -

پارامترها

- -
-
iterable
-
اگر یک شیء قابل شمارش (iterable) باشد، همه‌ی عناصر آن به مجموعه‌ی جدید ما اضافه می‌شوند. null نیز در این‌جا به منزله‌ی undefined است.
-
- -

توضیح

- -

هر شیء Set مجموعه‌ای از مقادیر است. این مقادیر به ترتیبی که به مجموعه اضافه شدند شمارش می‌شوند. یک مقدار در مجموعه فقط می‌تواند یک بار بیاید (مهم‌ترین تفاوت مجموعه و آرایه در همین است که در مجموعه مقدار تکراری نداریم ولی در آرایه می‌توانیم داشته باشیم).

- -

برابر بودن مقدارها

- -

از آن جایی که در هر مجموعه باید مقادیر منحصر به فرد داشته باشیم، به صورت خودکار هنگام اضافه شدن عضو جدید به مجموعه برابری مقدارها بررسی می‌شود. در نسخه‌های قبلی ECMAScript، الگوریتمی که این بررسی استفاده می‌کرد با الگوریتم عملگر === فرق داشت. مخصوصا برای مجموعه‌ها عدد صفر مثبت +0 با صفر منفی -0 متفاوت در نظر گرفته می‌شدند. با این حال در مشخّصاتی که برای ECMAScript 2015 در نظر گرفته شد این مورد تغییر کرد. برای اطّلاعات بیشتر جدول پشتیبانی مرورگرها از برابری صفر مثبت و منفی را ببینید.

- -

ضمناً NaN و undefined نیز می‌توانند در یک مجموعه ذخیره شوند. در این مورد NaN با NaN برابر در نظر گرفته می‌شود (در حالی که به صورت عادی NaN !== NaN است).

- -

خصیصه‌ها

- -
-
Set.length
-
مقدار خصیصه‌ی length همیشه 0 است!
-
{{jsxref("Set.@@species", "get Set[@@species]")}}
-
تابع سازنده‌ای است که برای اشیاء مشتق شده به کار می‌رود.
-
{{jsxref("Set.prototype")}}
-
نشان‌دهنده‌ی prototype تابع سازنده‌ی Set است که اجازه می‌دهد خصیصه‌های جدیدی را به تمام اشیائی که از نوع مجموعه هستند اضافه کنید.
-
- -

Set instances

- -

تمام نمونه‌های کلاس Set از {{jsxref("Set.prototype")}} ارث‌بری می‌کنند.

- -

خصیصه‌ها

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}

- -

متُدها

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}

- -

مثال‌ها

- -

استفاده از شیء Set

- -
var mySet = new Set();
-
-mySet.add(1);
-mySet.add(5);
-mySet.add("some text");
-var o = {a: 1, b: 2};
-mySet.add(o);
-
-mySet.add({a: 1, b: 2}); // o is referencing a different object so this is okay
-
-mySet.has(1); // true
-mySet.has(3); // false, 3 has not been added to the set
-mySet.has(5);              // true
-mySet.has(Math.sqrt(25));  // true
-mySet.has("Some Text".toLowerCase()); // true
-mySet.has(o); // true
-
-mySet.size; // 4
-
-mySet.delete(5); // removes 5 from the set
-mySet.has(5);    // false, 5 has been removed
-
-mySet.size; // 3, we just removed one value
-
- -

شمارش عناصر مجموعه

- -
// iterate over items in set
-// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
-for (let item of mySet) console.log(item);
-
-// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
-for (let item of mySet.keys()) console.log(item);
-
-// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
-for (let item of mySet.values()) console.log(item);
-
-// logs the items in the order: 1, "some text", {"a": 1, "b": 2}
-//(key and value are the same here)
-for (let [key, value] of mySet.entries()) console.log(key);
-
-// convert Set object to an Array object, with Array.from
-var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}]
-
-// the following will also work if run in an HTML document
-mySet.add(document.body);
-mySet.has(document.querySelector("body")); // true
-
-// converting between Set and Array
-mySet2 = new Set([1,2,3,4]);
-mySet2.size; // 4
-[...mySet2]; // [1,2,3,4]
-
-// intersect can be simulated via
-var intersection = new Set([...set1].filter(x => set2.has(x)));
-
-// difference can be simulated via
-var difference = new Set([...set1].filter(x => !set2.has(x)));
-
-// Iterate set entries with forEach
-mySet.forEach(function(value) {
-  console.log(value);
-});
-
-// 1
-// 2
-// 3
-// 4
- -

پیاده‌سازی عمل‌های اصلی در مجموعه‌ها

- -
Set.prototype.isSuperset = function(subset) {
-    for (var elem of subset) {
-        if (!this.has(elem)) {
-            return false;
-        }
-    }
-    return true;
-}
-
-Set.prototype.union = function(setB) {
-    var union = new Set(this);
-    for (var elem of setB) {
-        union.add(elem);
-    }
-    return union;
-}
-
-Set.prototype.intersection = function(setB) {
-    var intersection = new Set();
-    for (var elem of setB) {
-        if (this.has(elem)) {
-            intersection.add(elem);
-        }
-    }
-    return intersection;
-}
-
-Set.prototype.difference = function(setB) {
-    var difference = new Set(this);
-    for (var elem of setB) {
-        difference.delete(elem);
-    }
-    return difference;
-}
-
-//Examples
-var setA = new Set([1,2,3,4]),
-    setB = new Set([2,3]),
-    setC = new Set([3,4,5,6]);
-
-setA.isSuperset(setB); // => true
-setA.union(setC); // => Set [1, 2, 3, 4, 5, 6]
-setA.intersection(setC); // => Set [3, 4]
-setA.difference(setC); // => Set [1, 2]
-
-
- -

ارتباط مجموعه و آرایه

- -
var myArray = ["value1", "value2", "value3"];
-
-// Use the regular Set constructor to transform an Array into a Set
-var mySet = new Set(myArray);
-
-mySet.has("value1"); // returns true
-
-// Use the spread operator to transform a set into an Array.
-console.log([...mySet]); // Will show you exactly the same Array as myArray
- -

مشخّصات

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-set-objects', 'Set')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}{{Spec2('ESDraft')}} 
- -

سازگاری با مرورگرها

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ویژگیChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
پشتیبانی ساده -

{{ CompatChrome(38) }} [1]

-
12{{ CompatGeckoDesktop("13") }}{{ CompatIE("11") }}257.1
Constructor argument: new Set(iterable){{ CompatChrome(38) }}12{{ CompatGeckoDesktop("13") }}{{CompatNo}}259.0
iterable{{ CompatChrome(38) }}12{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Set.clear(){{ CompatChrome(38) }}12{{CompatGeckoDesktop("19")}}{{ CompatIE("11") }}257.1
Set.keys(), Set.values(), Set.entries(){{ CompatChrome(38) }}12{{CompatGeckoDesktop("24")}}{{CompatNo}}257.1
Set.forEach(){{ CompatChrome(38) }}12{{CompatGeckoDesktop("25")}}{{ CompatIE("11") }}257.1
Value equality for -0 and 0{{ CompatChrome(38) }}12{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatSafari(9)}}
Constructor argument: new Set(null){{CompatVersionUnknown}}12{{CompatGeckoDesktop("37")}}{{CompatIE(11)}}{{CompatVersionUnknown}}{{CompatSafari(7.1)}}
Monkey-patched add() in Constructor{{CompatVersionUnknown}}12{{CompatGeckoDesktop("37")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatSafari(9)}}
Set[@@species]{{ CompatChrome(51) }}13{{CompatGeckoDesktop("41")}}{{CompatNo}}{{ CompatOpera(38) }}{{CompatSafari(10)}}
Set() without new throws{{CompatVersionUnknown}}12{{CompatGeckoDesktop("42")}}{{CompatIE(11)}}{{CompatVersionUnknown}}9
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(38)}} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Set(iterable){{CompatNo}}{{CompatChrome(38)}}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}9
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Set.clear(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Set.keys(), Set.values(), Set.entries(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("24")}}{{CompatNo}}{{CompatNo}}8
Set.forEach(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Value equality for -0 and 0{{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}9
Constructor argument: new Set(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}8
Monkey-patched add() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}9
Set[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}10
Set() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}9
-
- -

[1] The feature was available behind a preference from Chrome 31. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

- -

مطالب مرتبط

- - -
diff --git a/files/fa/web/javascript/reference/index.html b/files/fa/web/javascript/reference/index.html deleted file mode 100644 index d78299497a..0000000000 --- a/files/fa/web/javascript/reference/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: مرجع جاوا اسکریپت -slug: Web/JavaScript/Reference -tags: - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference ---- -
{{JsSidebar}}
- -

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

- -

Global Objects

- -

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}
- -

Statements

- -

This chapter documents all the JavaScript statements and declarations.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
- -

Expressions and operators

- -

This chapter documents all the JavaScript expressions and operators.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
- -

Functions

- -

This chapter documents how to work with JavaScript functions to develop your applications.

- - - -

Additional reference pages

- - diff --git a/files/fa/web/javascript/reference/operators/index.html b/files/fa/web/javascript/reference/operators/index.html deleted file mode 100644 index 636cb3acca..0000000000 --- a/files/fa/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,302 +0,0 @@ ---- -title: Expressions and operators -slug: Web/JavaScript/Reference/Operators -tags: - - بازبینی - - جاوااسکریپت - - عملوند - - منابع -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -
این بخش از سند شامل تمامی عمل ها و عبارت و کلمات کلیدی بکار رفته در زبان برنامه نویسی جاوااسکریپت می باشد.
- -

دسته بندی عبارت و عمل ها

- -

لیست زیر براساس الفابت انگلیسی مرتب شده است

- -

عبارات اصلی

- -

عبارت عمومی و کلمات کلیدی اصلی در جاوا اسکریپت.

- -
-
{{jsxref("Operators/this", "this")}}
-
کلمه کلیدی this به محتوایی در درون تابعی که در آن نوشته شده است اشاره می کند.
-
{{jsxref("Operators/function", "function")}}
-
کلمه کلیدی function  ٫ تعریف کننده یک تابع است.
-
{{jsxref("Operators/class", "class")}}
-
کلمه کلیدی class  ٫ تعریف کننده یک کلاس است.
-
{{jsxref("Operators/function*", "function*")}}
-
کلمه کلیدی function*  تعریف کننده یک سازنده کلاس است.
-
{{jsxref("Operators/yield", "yield")}}
-
مکث و از سرگیری می کند تابعی که تولید شده است.
-
{{jsxref("Operators/yield*", "yield*")}}
-
محول می کند به تابع یا آبجکت تولید شده دیگر.
-
{{experimental_inline}} {{jsxref("Operators/async_function", "async function*")}}
-
async function  یک تابع async تعریف می کند
-
{{experimental_inline}} {{jsxref("Operators/await", "await")}}
-
مکث و از سرگیری می کند و تابع اسینک (async ) و منتظر اجازه  برای تایید را رد می ماند
-
{{jsxref("Global_Objects/Array", "[]")}}
-
تعریف کننده /سازنده یک آرایه .
-
{{jsxref("Operators/Object_initializer", "{}")}}
-
تعریف کننده / سازنده یک آبجکت ( شئی) .
-
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
-
یک ترکیب صحیح از عبارتها
-
{{jsxref("Operators/Grouping", "( )")}}
-
دسته بندی عمل ها
-
- -

عبارت های سمت چپ

- -

مقدارهای سمت چپ مشخص کردن  هدف هستند 

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
عمل های شامل درستی به یک ویژگی یا متد از یک آبجکت(شئی) از قبل تعریف شده
- (object.property  و object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
عمل new  یک سازنده از الگو یا موجودیت از قبل تعریف شده مثل آبجکت 
-
new.target
-
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
-
{{jsxref("Operators/super", "super")}}
-
کلیدواژه super  والد سازنده را صدا می زند
-
{{jsxref("Operators/Spread_operator", "...obj")}}
-
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
-
- -

افزایش و کاهش

- -

عملوند  پیشوندی/ پسوندی افزایشی و  عملوند پیشوندی/پسوندی کاهشی

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
عملوند پسوندی افزایشی.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
عملوند پسوندی کاهشی.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
عملوند پیشوندی افزایشی.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
عملوند پیشوند کاهشی
-
- -

عملوند های یکتا

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
عملوند delete  ویژگی /ها را از یک آبجکت حذف می کند.
-
{{jsxref("Operators/void", "void")}}
-
در عمل کننده void مقداری برای بازگشت از یک عبارت وجود ندارد.
-
{{jsxref("Operators/typeof", "typeof")}}
-
typeof  نوع آبجکت (شئی )دریافتی را مشخص می کند.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

عملوند های منطقی

- -

عملوندهای منطقی روی مقدار عددی اعمال می شوند و یک عدد به عنوان نتیجه منطقی  عملوند منطقی خواهد بود

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
عمل جمع.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
عمل تفریق/منها
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
عمل تقسیم
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
عمل ضرب
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
عمل تقسیم / خروجی باقیماند تقسیم
-
- -
-
{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
-
عمل توان
-
- -

Relational operators

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -
-

Note: => is not an operator, but the notation for Arrow functions.

-
- -

Equality operators

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Binary bitwise operators

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Binary logical operators

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Conditional (ternary) operator

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Assignment operators

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

-
-
- -

Comma operator

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
-
- -

Non-standard features

- -
-
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
-
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
-
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
-
The expression closure syntax is a shorthand for writing simple function.
-
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}}
- -

See also

- - diff --git a/files/fa/web/javascript/reference/statements/index.html b/files/fa/web/javascript/reference/statements/index.html deleted file mode 100644 index 368977efc8..0000000000 --- a/files/fa/web/javascript/reference/statements/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Statements and declarations -slug: Web/JavaScript/Reference/Statements -tags: - - JavaScript - - NeedsTranslation - - Reference - - TopicStub - - statements -translation_of: Web/JavaScript/Reference/Statements ---- -
{{jsSidebar("Statements")}}
- -

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

- -

Statements and declarations by category

- -

For an alphabetical listing see the sidebar on the left.

- -

Control flow

- -
-
{{jsxref("Statements/block", "Block")}}
-
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
-
{{jsxref("Statements/break", "break")}}
-
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
-
{{jsxref("Statements/continue", "continue")}}
-
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
-
{{jsxref("Statements/Empty", "Empty")}}
-
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
-
{{jsxref("Statements/if...else", "if...else")}}
-
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
-
{{jsxref("Statements/switch", "switch")}}
-
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
-
{{jsxref("Statements/throw", "throw")}}
-
Throws a user-defined exception.
-
{{jsxref("Statements/try...catch", "try...catch")}}
-
Marks a block of statements to try, and specifies a response, should an exception be thrown.
-
- -

Declarations

- -
-
{{jsxref("Statements/var", "var")}}
-
Declares a variable, optionally initializing it to a value.
-
{{experimental_inline}} {{jsxref("Statements/let", "let")}}
-
Declares a block scope local variable, optionally initializing it to a value.
-
{{experimental_inline}} {{jsxref("Statements/const", "const")}}
-
Declares a read-only named constant.
-
- -

Functions and classes

- -
-
{{jsxref("Statements/function", "function")}}
-
Declares a function with the specified parameters.
-
{{experimental_inline}} {{jsxref("Statements/function*", "function*")}}
-
Generators functions enable writing iterators more easily.
-
{{jsxref("Statements/return", "return")}}
-
Specifies the value to be returned by a function.
-
{{experimental_inline}} {{jsxref("Statements/class", "class")}}
-
Declares a class.
-
- -

Iterations

- -
-
{{jsxref("Statements/do...while", "do...while")}}
-
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
-
{{jsxref("Statements/for", "for")}}
-
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
-
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
-
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
-
{{jsxref("Statements/for...in", "for...in")}}
-
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
-
{{experimental_inline}} {{jsxref("Statements/for...of", "for...of")}}
-
Iterates over iterable objects (including arrays, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
-
{{jsxref("Statements/while", "while")}}
-
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
-
- -

Others

- -
-
{{jsxref("Statements/debugger", "debugger")}}
-
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
-
{{experimental_inline}} {{jsxref("Statements/export", "export")}}
-
Used to export functions to make them available for imports in external modules, another scripts.
-
{{experimental_inline}} {{jsxref("Statements/import", "import")}}
-
Used to import functions exported from an external module, another script.
-
{{jsxref("Statements/label", "label")}}
-
Provides a statement with an identifier that you can refer to using a break or continue statement.
-
- -
-
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
-
Extends the scope chain for a statement.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
- -

See also

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