diff options
author | Ryan Johnson <rjohnson@mozilla.com> | 2021-04-29 16:16:42 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-29 16:16:42 -0700 |
commit | 95aca4b4d8fa62815d4bd412fff1a364f842814a (patch) | |
tree | 5e57661720fe9058d5c7db637e764800b50f9060 /files/fa/web/javascript | |
parent | ee3b1c87e3c8e72ca130943eed260ad642246581 (diff) | |
download | translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.gz translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.tar.bz2 translated-content-95aca4b4d8fa62815d4bd412fff1a364f842814a.zip |
remove retired locales (#699)
Diffstat (limited to 'files/fa/web/javascript')
26 files changed, 0 insertions, 8786 deletions
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 ---- -<div>{{jsSidebar}}</div> - -<p>چرا دوباره معرفی شود؟ زیرا جاوااسکریپت از لحاظ ایجاد سوتفاهم در جهان مشهور است. این اغلب به عنوان یک اسباب بازی مورد تمسخر قرار می گیرد ، اما در زیر لایه ساده فریبنده آن ، ویژگی های قدرتمند زبان در انتظار است. جاوا اسکریپت اکنون توسط تعداد باورنکردنی از برنامه های با مشخصات بالا استفاده می شود ، نشان می دهد که دانش عمیق تر از این فن آوری مهارت مهمی برای هر توسعه دهنده وب یا تلفن همراه است.</p> - -<p>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.</p> - -<p>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 <a class="external" href="http://www.ecma-international.org/">Ecma International</a>, a European standards organization, which resulted in the first edition of the <a href="/en-US/docs/Glossary/ECMAScript">ECMAScript</a> standard that year. The standard received a significant update as <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript edition 3</a> 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.</p> - -<div class="note"> -<p>Because it is more familiar, we will refer to ECMAScript as "JavaScript" from this point on.</p> -</div> - -<p>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 <a href="http://nodejs.org/">Node.js</a>, NoSQL databases like the open source <a href="http://couchdb.apache.org/">Apache CouchDB</a>, embedded computers, complete desktop environments like <a href="http://www.gnome.org/">GNOME</a> (one of the most popular GUIs for GNU/Linux operating systems), and others.</p> - -<h2 id="Overview">Overview</h2> - -<p>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 <a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain" title="prototypical inheritance">prototypical inheritance</a> and ES2015 <a href="/en-US/docs/Web/JavaScript/Reference/Classes">classes</a>). JavaScript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object.</p> - -<p>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:</p> - -<ul> - <li>{{jsxref("Number")}}</li> - <li>{{jsxref("String")}}</li> - <li>{{jsxref("Boolean")}}</li> - <li>{{jsxref("Function")}}</li> - <li>{{jsxref("Object")}}</li> - <li>{{jsxref("Symbol")}} (new in ES2015)</li> -</ul> - -<p>... 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:</p> - -<ul> - <li>{{jsxref("Number")}}</li> - <li>{{jsxref("String")}}</li> - <li>{{jsxref("Boolean")}}</li> - <li>{{jsxref("Symbol")}} (new in ES2015)</li> - <li>{{jsxref("Object")}} - <ul> - <li>{{jsxref("Function")}}</li> - <li>{{jsxref("Array")}}</li> - <li>{{jsxref("Date")}}</li> - <li>{{jsxref("RegExp")}}</li> - </ul> - </li> - <li>{{jsxref("null")}}</li> - <li>{{jsxref("undefined")}}</li> -</ul> - -<p>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.</p> - -<h2 id="Numbers">Numbers</h2> - -<p>Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values", according to the spec — There's <strong><em>no such thing as an integer</em></strong> in JavaScript (except {{jsxref("BigInt")}}), so you have to be a little careful. See this example:</p> - -<pre class="syntaxbox notranslate">console.log(3 / 2); // 1.5, <em>not</em> 1 -console.log(Math.floor(3 / 2)); // 1</pre> - -<p>So an <em>apparent integer</em> is in fact <em>implicitly a float</em>.</p> - -<p>Also, watch out for stuff like:</p> - -<pre class="brush: js notranslate">0.1 + 0.2 == 0.30000000000000004; -</pre> - -<p>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.</p> - -<p>The standard <a href="/en-US/docs/Web/JavaScript/Reference/Operators#Arithmetic_operators">arithmetic operators</a> 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:</p> - -<pre class="brush: js notranslate">Math.sin(3.5); -var circumference = 2 * Math.PI * r; -</pre> - -<p>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:</p> - -<pre class="brush: js notranslate">parseInt('123', 10); // 123 -parseInt('010', 10); // 10 -</pre> - -<p>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:</p> - -<pre class="brush: js notranslate">parseInt('010'); // 8 -parseInt('0x10'); // 16 -</pre> - -<p>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 <em>hexadecimal notation is still in place</em>; only octal has been removed.</p> - -<p>If you want to convert a binary number to an integer, just change the base:</p> - -<pre class="brush: js notranslate">parseInt('11', 2); // 3 -</pre> - -<p>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, <code>parseFloat()</code> always uses base 10.</p> - -<p>You can also use the unary <code>+</code> operator to convert values to numbers:</p> - -<pre class="brush: js notranslate">+ '42'; // 42 -+ '010'; // 10 -+ '0x10'; // 16 -</pre> - -<p>A special value called {{jsxref("NaN")}} (short for "Not a Number") is returned if the string is non-numeric:</p> - -<pre class="brush: js notranslate">parseInt('hello', 10); // NaN -</pre> - -<p><code>NaN</code> is toxic: if you provide it as an operand to any mathematical operation, the result will also be <code>NaN</code>:</p> - -<pre class="brush: js notranslate">NaN + 5; // NaN -</pre> - -<p>You can test for <code>NaN</code> using the built-in {{jsxref("Global_Objects/isNaN", "isNaN()")}} function:</p> - -<pre class="brush: js notranslate">isNaN(NaN); // true -</pre> - -<p>JavaScript also has the special values {{jsxref("Infinity")}} and <code>-Infinity</code>:</p> - -<pre class="brush: js notranslate"> 1 / 0; // Infinity --1 / 0; // -Infinity -</pre> - -<p>You can test for <code>Infinity</code>, <code>-Infinity</code> and <code>NaN</code> values using the built-in {{jsxref("Global_Objects/isFinite", "isFinite()")}} function:</p> - -<pre class="brush: js notranslate">isFinite(1 / 0); // false -isFinite(-Infinity); // false -isFinite(NaN); // false -</pre> - -<div class="note">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 <code>NaN</code> 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.</div> - -<h2 id="Strings">Strings</h2> - -<p>Strings in JavaScript are sequences of <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">Unicode characters</a>. 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.</p> - -<p>If you want to represent a single character, you just use a string consisting of that single character.</p> - -<p>To find the length of a string (in code units), access its <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length">length</a></code> property:</p> - -<pre class="brush: js notranslate">'hello'.length; // 5 -</pre> - -<p>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:</p> - -<pre class="brush: js notranslate">'hello'.charAt(0); // "h" -'hello, world'.replace('world', 'mars'); // "hello, mars" -'hello'.toUpperCase(); // "HELLO" -</pre> - -<h2 id="Other_types">Other types</h2> - -<p>JavaScript distinguishes between {{jsxref("null")}}, which is a value that indicates a deliberate non-value (and is only accessible through the <code>null</code> keyword), and {{jsxref("undefined")}}, which is a value of type <code>undefined</code> 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 <code>undefined</code>. <code>undefined</code> is actually a constant.</p> - -<p>JavaScript has a boolean type, with possible values <code>true</code> and <code>false</code> (both of which are keywords.) Any value can be converted to a boolean according to the following rules:</p> - -<ol> - <li><code>false</code>, <code>0</code>, empty strings (<code>""</code>), <code>NaN</code>, <code>null</code>, and <code>undefined</code> all become <code>false.</code></li> - <li>All other values become <code>true.</code></li> -</ol> - -<p>You can perform this conversion explicitly using the <code>Boolean()</code> function:</p> - -<pre class="brush: js notranslate">Boolean(''); // false -Boolean(234); // true -</pre> - -<p>However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an <code>if</code> statement (see below). For this reason, we sometimes speak simply of "true values" and "false values," meaning values that become <code>true</code> and <code>false</code>, respectively, when converted to booleans. Alternatively, such values can be called "truthy" and "falsy", respectively.</p> - -<p>Boolean operations such as <code>&&</code> (logical <em>and</em>), <code>||</code> (logical <em>or</em>), and <code>!</code> (logical <em>not</em>) are supported; see below.</p> - -<h2 id="Variables">Variables</h2> - -<p>New variables in JavaScript are declared using one of three keywords: <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code>, or <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var" title="/en/JavaScript/Reference/Statements/var">var</a></code>.<br> - <br> - <strong><code>let</code> </strong>allows you to declare block-level variables. The declared variable is available from the <em>block</em> it is enclosed in.</p> - -<pre class="brush: js notranslate">let a; -let name = 'Simon'; -</pre> - -<p>The following is an example of scope with a variable declared with <code><strong>let</strong></code>:</p> - -<pre class="brush: js notranslate">// 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 - -</pre> - -<p><code><strong>const</strong></code> allows you to declare variables whose values are never intended to change. The variable is available from the <em>block</em> it is declared in.</p> - -<pre class="brush: js notranslate">const Pi = 3.14; // variable Pi is set -Pi = 1; // will throw an error because you cannot change a constant variable.</pre> - -<p><br> - <code><strong>var</strong></code> 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 <strong><code>var</code> </strong>keyword is available from the <em>function</em> it is declared in.</p> - -<pre class="brush: js notranslate">var a; -var name = 'Simon';</pre> - -<p>An example of scope with a variable declared with <strong><code>var</code>:</strong></p> - -<pre class="brush: js notranslate">// myVarVariable *is* visible out here - -for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) { - // myVarVariable is visible to the whole function -} - -// myVarVariable *is* visible out here -</pre> - -<p>If you declare a variable without assigning any value to it, its type is <code>undefined</code>.</p> - -<p>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 <code>var</code> in a compound statement (for example inside an <code>if</code> control structure), it will be visible to the entire function. However, starting with ECMAScript 2015, <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code> and <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code> declarations allow you to create block-scoped variables.</p> - -<h2 id="Operators">Operators</h2> - -<p>JavaScript's numeric operators are <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> and <code>%</code> which is the remainder operator (<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_%28%29">which is the same as modulo</a>.) Values are assigned using <code>=</code>, and there are also compound assignment statements such as <code>+=</code> and <code>-=</code>. These extend out to <code>x = x <em>operator</em> y</code>.</p> - -<pre class="brush: js notranslate">x += 5; -x = x + 5; -</pre> - -<p>You can use <code>++</code> and <code>--</code> to increment and decrement respectively. These can be used as a prefix or postfix operators.</p> - -<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition" title="/en/JavaScript/Reference/Operators/String_Operators"><code>+</code> operator</a> also does string concatenation:</p> - -<pre class="brush: js notranslate">'hello' + ' world'; // "hello world" -</pre> - -<p>If you add a string to a number (or other value) everything is converted into a string first. This might trip you up:</p> - -<pre class="brush: js notranslate">'3' + 4 + 5; // "345" - 3 + 4 + '5'; // "75" -</pre> - -<p>Adding an empty string to something is a useful way of converting it to a string itself.</p> - -<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators" title="/en/JavaScript/Reference/Operators/Comparison_Operators">Comparisons</a> in JavaScript can be made using <code><</code>, <code>></code>, <code><=</code> and <code>>=</code>. 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:</p> - -<pre class="brush: js notranslate">123 == '123'; // true -1 == true; // true -</pre> - -<p>To avoid type coercion, use the triple-equals operator:</p> - -<pre class="brush: js notranslate">123 === '123'; // false -1 === true; // false -</pre> - -<p>There are also <code>!=</code> and <code>!==</code> operators.</p> - -<p>JavaScript also has <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators" title="/en/JavaScript/Reference/Operators/Bitwise_Operators">bitwise operations</a>. If you want to use them, they're there.</p> - -<h2 id="Control_structures">Control structures</h2> - -<p>JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by <code>if</code> and <code>else</code>; you can chain them together if you like:</p> - -<pre class="brush: js notranslate">var name = 'kittens'; -if (name == 'puppies') { - name += ' woof'; -} else if (name == 'kittens') { - name += ' meow'; -} else { - name += '!'; -} -name == 'kittens meow'; -</pre> - -<p>JavaScript has <code>while</code> loops and <code>do-while</code> 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:</p> - -<pre class="brush: js notranslate">while (true) { - // an infinite loop! -} - -var input; -do { - input = get_input(); -} while (inputIsNotValid(input)); -</pre> - -<p>JavaScript's <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for"><code>for</code> loop</a> is the same as that in C and Java: it lets you provide the control information for your loop on a single line.</p> - -<pre class="brush: js notranslate">for (var i = 0; i < 5; i++) { - // Will execute 5 times -} -</pre> - -<p>JavaScript also contains two other prominent for loops: <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for</code>...<code>of</code></a></p> - -<pre class="brush: js notranslate">for (let value of array) { - // do something with value -} -</pre> - -<p>and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for</code>...<code>in</code></a>:</p> - -<pre class="brush: js notranslate">for (let property in object) { - // do something with object property -} -</pre> - -<p>The <code>&&</code> and <code>||</code> 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:</p> - -<pre class="brush: js notranslate">var name = o && o.getName(); -</pre> - -<p>Or for caching values (when falsy values are invalid):</p> - -<pre class="brush: js notranslate">var name = cachedName || (cachedName = getName()); -</pre> - -<p>JavaScript has a ternary operator for conditional expressions:</p> - -<pre class="brush: js notranslate">var allowed = (age > 18) ? 'yes' : 'no'; -</pre> - -<p>The <code>switch</code> statement can be used for multiple branches based on a number or string:</p> - -<pre class="brush: js notranslate">switch (action) { - case 'draw': - drawIt(); - break; - case 'eat': - eatIt(); - break; - default: - doNothing(); -} -</pre> - -<p>If you don't add a <code>break</code> 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:</p> - -<pre class="brush: js notranslate">switch (a) { - case 1: // fallthrough - case 2: - eatIt(); - break; - default: - doNothing(); -} -</pre> - -<p>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 <code>===</code> operator:</p> - -<pre class="brush: js notranslate">switch (1 + 3) { - case 2 + 2: - yay(); - break; - default: - neverhappens(); -} -</pre> - -<h2 id="Objects">Objects</h2> - -<p>JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to:</p> - -<ul> - <li>Dictionaries in Python.</li> - <li>Hashes in Perl and Ruby.</li> - <li>Hash tables in C and C++.</li> - <li>HashMaps in Java.</li> - <li>Associative arrays in PHP.</li> -</ul> - -<p>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!</p> - -<p>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.</p> - -<p>There are two basic ways to create an empty object:</p> - -<pre class="brush: js notranslate">var obj = new Object(); -</pre> - -<p>And:</p> - -<pre class="brush: js notranslate">var obj = {}; -</pre> - -<p>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.</p> - -<p>Object literal syntax can be used to initialize an object in its entirety:</p> - -<pre class="brush: js notranslate">var obj = { - name: 'Carrot', - for: 'Max', // 'for' is a reserved word, use '_for' instead. - details: { - color: 'orange', - size: 12 - } -}; -</pre> - -<p>Attribute access can be chained together:</p> - -<pre class="brush: js notranslate">obj.details.color; // orange -obj['details']['size']; // 12 -</pre> - -<p>The following example creates an object prototype(<code>Person</code>) and an instance of that prototype(<code>you</code>).</p> - -<pre class="brush: js notranslate">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. - -</pre> - -<p><strong>Once created</strong>, an object's properties can again be accessed in one of two ways:</p> - -<pre class="brush: js notranslate">// dot notation -obj.name = 'Simon'; -var name = obj.name; -</pre> - -<p>And...</p> - -<pre class="brush: js notranslate">// 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?') -</pre> - -<p>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 <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords" title="/en/JavaScript/Reference/Reserved_Words">reserved words</a>:</p> - -<pre class="brush: js notranslate">obj.for = 'Simon'; // Syntax error, because 'for' is a reserved word -obj['for'] = 'Simon'; // works fine -</pre> - -<div class="note"> -<p>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 <a href="http://es5.github.io/#x7.6.1">Spec</a>.</p> -</div> - -<p>For more on objects and prototypes see <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype">Object.prototype</a>. For an explanation of object prototypes and the object prototype chains see <a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a>.</p> - -<div class="note"> -<p>Starting in ECMAScript 2015, object keys can be defined by the variable using bracket notation upon being created. <code>{[phoneType]: 12345}</code> is possible instead of just <code>var userPhone = {}; userPhone[phoneType] = 12345</code>.</p> -</div> - -<h2 id="Arrays">Arrays</h2> - -<p>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 <code>[]</code> syntax) but they have one magic property called '<code>length</code>'. This is always one more than the highest index in the array.</p> - -<p>One way of creating arrays is as follows:</p> - -<pre class="brush: js notranslate">var a = new Array(); -a[0] = 'dog'; -a[1] = 'cat'; -a[2] = 'hen'; -a.length; // 3 -</pre> - -<p>A more convenient notation is to use an array literal:</p> - -<pre class="brush: js notranslate">var a = ['dog', 'cat', 'hen']; -a.length; // 3 -</pre> - -<p>Note that <code>array.length</code> isn't necessarily the number of items in the array. Consider the following:</p> - -<pre class="brush: js notranslate">var a = ['dog', 'cat', 'hen']; -a[100] = 'fox'; -a.length; // 101 -</pre> - -<p>Remember — the length of the array is one more than the highest index.</p> - -<p>If you query a non-existent array index, you'll get a value of <code>undefined</code> in return:</p> - -<pre class="brush: js notranslate">typeof a[90]; // undefined -</pre> - -<p>If you take the above about <code>[]</code> and <code>length</code> into account, you can iterate over an array using the following <code>for</code> loop:</p> - -<pre class="brush: js notranslate">for (var i = 0; i < a.length; i++) { - // Do something with a[i] -} -</pre> - -<p>ES2015 introduced the more concise <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for</code>...<code>of</code></a> loop for iterable objects such as arrays:</p> - -<pre class="brush:js notranslate">for (const currentValue of a) { - // Do something with currentValue -}</pre> - -<p>You could also iterate over an array using a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in" title="/en/JavaScript/Reference/Statements/for...in"><code>for</code>...<code>in</code></a> loop, however this does not iterate over the array elements, but the array indices. Furthermore, if someone added new properties to <code>Array.prototype</code>, they would also be iterated over by such a loop. Therefore this loop type is not recommended for arrays.</p> - -<p>Another way of iterating over an array that was added with ECMAScript 5 is <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach()</a></code>:</p> - -<pre class="brush: js notranslate">['dog', 'cat', 'hen'].forEach(function(currentValue, index, array) { - // Do something with currentValue or array[index] -}); -</pre> - -<p>If you want to append an item to an array simply do it like this:</p> - -<pre class="brush: js notranslate">a.push(item);</pre> - -<p>Arrays come with a number of methods. See also the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">full documentation for array methods</a>.</p> - -<table> - <thead> - <tr> - <th scope="col">Method name</th> - <th scope="col">Description</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>a.toString()</code></td> - <td>Returns a string with the <code>toString()</code> of each element separated by commas.</td> - </tr> - <tr> - <td><code>a.toLocaleString()</code></td> - <td>Returns a string with the <code>toLocaleString()</code> of each element separated by commas.</td> - </tr> - <tr> - <td><code>a.concat(item1[, item2[, ...[, itemN]]])</code></td> - <td>Returns a new array with the items added on to it.</td> - </tr> - <tr> - <td><code>a.join(sep)</code></td> - <td>Converts the array to a string — with values delimited by the <code>sep</code> param</td> - </tr> - <tr> - <td><code>a.pop()</code></td> - <td>Removes and returns the last item.</td> - </tr> - <tr> - <td><code>a.push(item1, ..., itemN)</code></td> - <td>Appends items to the end of the array.</td> - </tr> - <tr> - <td><code>a.shift()</code></td> - <td>Removes and returns the first item.</td> - </tr> - <tr> - <td><code>a.unshift(item1[, item2[, ...[, itemN]]])</code></td> - <td>Prepends items to the start of the array.</td> - </tr> - <tr> - <td><code>a.slice(start[, end])</code></td> - <td>Returns a sub-array.</td> - </tr> - <tr> - <td><code>a.sort([cmpfn])</code></td> - <td>Takes an optional comparison function.</td> - </tr> - <tr> - <td><code>a.splice(start, delcount[, item1[, ...[, itemN]]])</code></td> - <td>Lets you modify an array by deleting a section and replacing it with more items.</td> - </tr> - <tr> - <td><code>a.reverse()</code></td> - <td>Reverses the array.</td> - </tr> - </tbody> -</table> - -<h2 id="Functions">Functions</h2> - -<p>Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:</p> - -<pre class="brush: js notranslate">function add(x, y) { - var total = x + y; - return total; -} -</pre> - -<p>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 <code>return</code> 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 <code>undefined</code>.</p> - -<p>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 <code>undefined</code>.</p> - -<pre class="brush: js notranslate">add(); // NaN -// You can't perform addition on undefined -</pre> - -<p>You can also pass in more arguments than the function is expecting:</p> - -<pre class="brush: js notranslate">add(2, 3, 4); // 5 -// added the first two; 4 was ignored -</pre> - -<p>That may seem a little silly, but functions have access to an additional variable inside their body called <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments" title="/en/JavaScript/Reference/Functions_and_function_scope/arguments"><code>arguments</code></a>, 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:</p> - -<pre class="brush: js notranslate">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 -</pre> - -<p>That's really not any more useful than writing <code>2 + 3 + 4 + 5</code> though. Let's create an averaging function:</p> - -<pre class="brush: js notranslate">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 -</pre> - -<p>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 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameter syntax</a>. In this way, we can pass in any number of arguments into the function while keeping our code minimal. The <strong>rest parameter operator</strong> is used in function parameter lists with the format: <strong>...variable</strong> and it will include within that variable the entire list of uncaptured arguments that the function was called with. We will also replace the <strong>for</strong> loop with a <strong>for...of</strong> loop to return the values within our variable.</p> - -<pre class="brush: js notranslate">function avg(...args) { - var sum = 0; - for (let value of args) { - sum += value; - } - return sum / args.length; -} - -avg(2, 3, 4, 5); // 3.5 -</pre> - -<div class="note">In the above code, the variable <strong>args</strong> holds all the values that were passed into the function.<br> -<br> -It is important to note that wherever the rest parameter operator is placed in a function declaration it will store all arguments <em>after</em> its declaration, but not before. <em>i.e. function</em> <em>avg(</em><strong>firstValue, </strong><em>...args)</em><strong> </strong>will store the first value passed into the function in the <strong>firstValue </strong>variable and the remaining arguments in <strong>args</strong>. That's another useful language feature but it does lead us to a new problem. The <code>avg()</code> 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:</div> - -<pre class="brush: js notranslate">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 -</pre> - -<p>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.</p> - -<pre class="brush: js notranslate">avg.apply(null, [2, 3, 4, 5]); // 3.5 -</pre> - -<p>The second argument to <code>apply()</code> is the array to use as arguments; the first will be discussed later on. This emphasizes the fact that functions are objects too.</p> - -<div class="note"> -<p>You can achieve the same result using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a> in the function call.</p> - -<p>For instance: <code>avg(...numbers)</code></p> -</div> - -<p>JavaScript lets you create anonymous functions.</p> - -<pre class="brush: js notranslate">var avg = function() { - var sum = 0; - for (var i = 0, j = arguments.length; i < j; i++) { - sum += arguments[i]; - } - return sum / arguments.length; -}; -</pre> - -<p>This is semantically equivalent to the <code>function avg()</code> 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:</p> - -<pre class="brush: js notranslate">var a = 1; -var b = 2; - -(function() { - var b = 3; - a += b; -})(); - -a; // 4 -b; // 2 -</pre> - -<p>JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.</p> - -<pre class="brush: js notranslate">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; -} -</pre> - -<p>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 <a href="/en-US/docs/Glossary/IIFE">IIFEs (Immediately Invoked Function Expressions)</a> as shown below:</p> - -<pre class="brush: js notranslate">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); -</pre> - -<p>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.</p> - -<p>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.</p> - -<h2 id="Custom_objects">Custom objects</h2> - -<div class="note">For a more detailed discussion of object-oriented programming in JavaScript, see <a href="/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Introduction to Object-Oriented JavaScript</a>.</div> - -<p>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:</p> - -<pre class="brush: js notranslate">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" -</pre> - -<p>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:</p> - -<pre class="brush: js notranslate">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" -</pre> - -<p>Note on the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this" title="/en/JavaScript/Reference/Operators/this">this</a></code> keyword. Used inside a function, <code>this</code> 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 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Accessing_properties" title="/en/JavaScript/Reference/Operators/Member_Operators">dot notation or bracket notation</a> on an object, that object becomes <code>this</code>. If dot notation wasn't used for the call, <code>this</code> refers to the global object.</p> - -<p>Note that <code>this</code> is a frequent cause of mistakes. For example:</p> - -<pre class="brush: js notranslate">var s = makePerson('Simon', 'Willison'); -var fullName = s.fullName; -fullName(); // undefined undefined -</pre> - -<p>When we call <code>fullName()</code> alone, without using <code>s.fullName()</code>, <code>this</code> is bound to the global object. Since there are no global variables called <code>first</code> or <code>last</code> we get <code>undefined</code> for each one.</p> - -<p>We can take advantage of the <code>this</code> keyword to improve our <code>makePerson</code> function:</p> - -<pre class="brush: js notranslate">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'); -</pre> - -<p>We have introduced another keyword: <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new" title="/en/JavaScript/Reference/Operators/new">new</a></code>. <code>new</code> is strongly related to <code>this</code>. It creates a brand new empty object, and then calls the function specified, with <code>this</code> set to that new object. Notice though that the function specified with <code>this</code> does not return a value but merely modifies the <code>this</code> object. It's <code>new</code> that returns the <code>this</code> object to the calling site. Functions that are designed to be called by <code>new</code> are called constructor functions. Common practice is to capitalize these functions as a reminder to call them with <code>new</code>.</p> - -<p>The improved function still has the same pitfall with calling <code>fullName()</code> alone.</p> - -<p>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?</p> - -<pre class="brush: js notranslate">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; -} -</pre> - -<p>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:</p> - -<pre class="brush: js notranslate">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; -}; -</pre> - -<p><code>Person.prototype</code> is an object shared by all instances of <code>Person</code>. It forms part of a lookup chain (that has a special name, "prototype chain"): any time you attempt to access a property of <code>Person</code> that isn't set, JavaScript will check <code>Person.prototype</code> to see if that property exists there instead. As a result, anything assigned to <code>Person.prototype</code> becomes available to all instances of that constructor via the <code>this</code> object.</p> - -<p>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:</p> - -<pre class="brush: js notranslate">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" -</pre> - -<p>Interestingly, you can also add things to the prototype of built-in JavaScript objects. Let's add a method to <code>String</code> that returns that string in reverse:</p> - -<pre class="brush: js notranslate">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 -</pre> - -<p>Our new method even works on string literals!</p> - -<pre class="brush: js notranslate">'This can now be reversed'.reversed(); // desrever eb won nac sihT -</pre> - -<p>As mentioned before, the prototype forms part of a chain. The root of that chain is <code>Object.prototype</code>, whose methods include <code>toString()</code> — it is this method that is called when you try to represent an object as a string. This is useful for debugging our <code>Person</code> objects:</p> - -<pre class="brush: js notranslate">var s = new Person('Simon', 'Willison'); -s.toString(); // [object Object] - -Person.prototype.toString = function() { - return '<Person: ' + this.fullName() + '>'; -} - -s.toString(); // "<Person: Simon Willison>" -</pre> - -<p>Remember how <code>avg.apply()</code> had a null first argument? We can revisit that now. The first argument to <code>apply()</code> is the object that should be treated as '<code>this</code>'. For example, here's a trivial implementation of <code>new</code>:</p> - -<pre class="brush: js notranslate">function trivialNew(constructor, ...args) { - var o = {}; // Create an object - constructor.apply(o, args); - return o; -} -</pre> - -<p>This isn't an exact replica of <code>new</code> 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, <code>...args</code> (including the ellipsis) is called the "<a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest arguments</a>" — as the name implies, this contains the rest of the arguments.</p> - -<p>Calling</p> - -<pre class="brush: js notranslate">var bill = trivialNew(Person, 'William', 'Orange');</pre> - -<p>is therefore almost equivalent to</p> - -<pre class="brush: js notranslate">var bill = new Person('William', 'Orange');</pre> - -<p><code>apply()</code> has a sister function named <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="/en/JavaScript/Reference/Global_Objects/Function/call"><code>call</code></a>, which again lets you set <code>this</code> but takes an expanded argument list as opposed to an array.</p> - -<pre class="brush: js notranslate">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 -</pre> - -<h3 id="Inner_functions">Inner functions</h3> - -<p>JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier <code>makePerson()</code> function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:</p> - -<pre class="brush: js notranslate">function parentFunc() { - var a = 1; - - function nestedFunc() { - var b = 4; // parentFunc can't use this - return a + b; - } - return nestedFunc(); // 5 -} -</pre> - -<p>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.</p> - -<p>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.</p> - -<h2 id="Closures">Closures</h2> - -<p>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?</p> - -<pre class="brush: js notranslate">function makeAdder(a) { - return function(b) { - return a + b; - }; -} -var add5 = makeAdder(5); -var add20 = makeAdder(20); -add5(6); // ? -add20(7); // ? -</pre> - -<p>The name of the <code>makeAdder()</code> 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.</p> - -<p>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 <em>do</em> still exist — otherwise, the adder functions would be unable to work. What's more, there are two different "copies" of <code>makeAdder()</code>'s local variables — one in which <code>a</code> is 5 and the other one where <code>a</code> is 20. So the result of that function calls is as follows:</p> - -<pre class="brush: js notranslate">add5(6); // returns 11 -add20(7); // returns 27 -</pre> - -<p>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 <code>this</code> and in browsers as <code>window</code>) 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.</p> - -<p>So when <code>makeAdder()</code> is called, a scope object is created with one property: <code>a</code>, which is the argument passed to the <code>makeAdder()</code> function. <code>makeAdder()</code> then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope object created for <code>makeAdder()</code> 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 <code>makeAdder()</code> returned.</p> - -<p>Scope objects form a chain called the scope chain, similar to the prototype chain used by JavaScript's object system.</p> - -<p>A <strong>closure</strong> 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 <a href="http://stackoverflow.com/questions/111102/how-do-javascript-closures-work">several excellent introductions to closures</a>.</p> 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 ---- -<pre>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}</pre> - -<p class="summary">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.</p> - -<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript reference</a> contains exhaustive details about the statements in this chapter. The semicolon (<code>;</code>) character is used to separate statements in JavaScript code.</p> - -<p>Any JavaScript expression is also a statement. See <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a> for complete information about expressions.</p> - -<h2 id="Block_statement">Block statement</h2> - -<p>The most basic statement is a block statement that is used to group statements. The block is delimited by a pair of curly brackets:</p> - -<pre class="syntaxbox">{ - statement_1; - statement_2; - . - . - . - statement_n; -} -</pre> - -<h3 id="Example"><strong>Example</strong></h3> - -<p>Block statements are commonly used with control flow statements (e.g. <code>if</code>, <code>for</code>, <code>while</code>).</p> - -<pre class="brush: js">while (x < 10) { - x++; -} -</pre> - -<p>Here, <code>{ x++; }</code> is the block statement.</p> - -<p><strong>Important</strong>: JavaScript prior to ECMAScript2015 does <strong>not</strong> 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:</p> - -<pre class="brush: js">var x = 1; -{ - var x = 2; -} -console.log(x); // outputs 2 -</pre> - -<p>This outputs 2 because the <code>var x</code> statement within the block is in the same scope as the <code>var x</code> statement before the block. In C or Java, the equivalent code would have outputted 1.</p> - -<p>Starting with ECMAScript2015, the <code>let</code> variable declaration is block scoped. See the {{jsxref("Statements/let", "let")}} reference page for more information.</p> - -<h2 id="Conditional_statements">Conditional statements</h2> - -<p>A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: <code>if...else</code> and <code>switch</code>.</p> - -<h3 id="if...else_statement"><code>if...else</code> statement</h3> - -<p>Use the <code>if</code> statement to execute a statement if a logical condition is true. Use the optional <code>else</code> clause to execute a statement if the condition is false. An <code>if</code> statement looks as follows:</p> - -<p>if (condition) {<br> - statement_1;<br> - } else {<br> - statement_2;<br> - }</p> - -<p>Here the<code> condition</code> can be any expression that evaluates to true or false. See <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description">Boolean</a> for an explanation of what evaluates to <code>true</code> and <code>false</code>. If <code>condition</code> evaluates to true, <code>statement_1</code> is executed; otherwise, <code>statement_2</code> is executed. <code>statement_1</code> and <code>statement_2</code> can be any statement, including further nested <code>if</code> statements.</p> - -<p>You may also compound the statements using <code>else if</code> to have multiple conditions tested in sequence, as follows:</p> - -<pre class="syntaxbox">if (condition_1) { - statement_1; -} else if (condition_2) { - statement_2; -} else if (condition_n) { - statement_n; -} else { - statement_last; -} -</pre> - -<p>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 (<code>{ ... }</code>) . In general, it's good practice to always use block statements, especially when nesting <code>if</code> statements:</p> - -<pre class="syntaxbox">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; -} -</pre> - -<div>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:</div> - -<pre class="example-bad brush: js">if (x = y) { - /* statements here */ -} -</pre> - -<p>If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:</p> - -<pre class="brush: js">if ((x = y)) { - /* statements here */ -} -</pre> - -<h4 id="Falsy_values">Falsy values</h4> - -<p>The following values evaluate to false (also known as {{Glossary("Falsy")}} values):</p> - -<ul> - <li><code>false</code></li> - <li><code>undefined</code></li> - <li><code>null</code></li> - <li><code>0</code></li> - <li><code>NaN</code></li> - <li>the empty string (<code>""</code>)</li> -</ul> - -<p>All other values, including all objects, evaluate to true when passed to a conditional statement.</p> - -<p>Do not confuse the primitive boolean values <code>true</code> and <code>false</code> with the true and false values of the {{jsxref("Boolean")}} object. For example:</p> - -<pre class="brush: js">var b = new Boolean(false); -if (b) // this condition evaluates to true -if (b == true) // this condition evaluates to false -</pre> - -<h4 id="Example_2"><strong>Example</strong></h4> - -<p>In the following example, the function <code>checkData</code> returns <code>true</code> if the number of characters in a <code>Text</code> object is three; otherwise, it displays an alert and returns <code>false</code>.</p> - -<pre class="brush: js">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; - } -} -</pre> - -<h3 id="switch_statement"><code>switch</code> statement</h3> - -<p>A <code>switch</code> 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 <code>switch</code> statement looks as follows:</p> - -<pre class="syntaxbox">switch (expression) { - case label_1: - statements_1 - [break;] - case label_2: - statements_2 - [break;] - ... - default: - statements_def - [break;] -} -</pre> - -<p>The program first looks for a <code>case</code> 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 <code>default</code> clause, and if found, transfers control to that clause, executing the associated statements. If no <code>default</code> clause is found, the program continues execution at the statement following the end of <code>switch</code>. By convention, the <code>default</code> clause is the last clause, but it does not need to be so.</p> - -<p>The optional <code>break</code> statement associated with each <code>case</code> clause ensures that the program breaks out of <code>switch</code> once the matched statement is executed and continues execution at the statement following switch. If <code>break</code> is omitted, the program continues execution at the next statement in the <code>switch</code> statement.</p> - -<h4 id="Example_3"><strong>Example</strong></h4> - -<p>In the following example, if <code>fruittype</code> evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When <code>break</code> is encountered, the program terminates <code>switch</code> and executes the statement following <code>switch</code>. If <code>break</code> were omitted, the statement for case "Cherries" would also be executed.</p> - -<pre class="brush: js">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?");</pre> - -<h2 id="Exception_handling_statements">Exception handling statements</h2> - -<p>You can throw exceptions using the <code>throw</code> statement and handle them using the <code>try...catch</code> statements.</p> - -<ul> - <li><a href="#throw_statement"><code>throw</code> statement</a></li> - <li><a href="#try...catch_statement"><code>try...catch</code> statement</a></li> -</ul> - -<h3 id="Exception_types">Exception types</h3> - -<p>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:</p> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects#Fundamental_objects">ECMAScript exceptions</a></li> - <li>{{domxref("DOMException")}} and {{domxref("DOMError")}}</li> -</ul> - -<h3 id="throw_statement"><code>throw</code> statement</h3> - -<p>Use the <code>throw</code> statement to throw an exception. When you throw an exception, you specify the expression containing the value to be thrown:</p> - -<pre class="syntaxbox">throw expression; -</pre> - -<p>You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:</p> - -<pre class="brush: js">throw "Error2"; // String type -throw 42; // Number type -throw true; // Boolean type -throw {toString: function() { return "I'm an object!"; } }; -</pre> - -<div class="note"><strong>Note:</strong> You can specify an object when you throw an exception. You can then reference the object's properties in the <code>catch</code> block. The following example creates an object <code>myUserException</code> of type <code>UserException</code> and uses it in a throw statement.</div> - -<pre class="brush: js">// 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");</pre> - -<h3 id="try...catch_statement"><code>try...catch</code> statement</h3> - -<p>The <code>try...catch</code> 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 <code>try...catch</code> statement catches it.</p> - -<p>The <code>try...catch</code> statement consists of a <code>try</code> block, which contains one or more statements, and a <code>catch</code> block, containing statements that specify what to do if an exception is thrown in the <code>try</code> block. That is, you want the <code>try</code> block to succeed, and if it does not succeed, you want control to pass to the <code>catch</code> block. If any statement within the <code>try</code> block (or in a function called from within the <code>try</code> block) throws an exception, control immediately shifts to the <code>catch</code> block. If no exception is thrown in the <code>try</code> block, the <code>catch</code> block is skipped. The <code>finally</code> block executes after the <code>try</code> and <code>catch</code> blocks execute but before the statements following the <code>try...catch</code> statement.</p> - -<p>The following example uses a <code>try...catch</code> 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 <code>"InvalidMonthNo"</code> and the statements in the <code>catch</code> block set the <code>monthName</code> variable to <code>unknown</code>.</p> - -<pre class="brush: js">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 -} -</pre> - -<h4 id="The_catch_block">The <code>catch</code> block</h4> - -<p>You can use a <code>catch</code> block to handle all exceptions that may be generated in the <code>try</code> block.</p> - -<pre class="syntaxbox">catch (catchID) { - statements -} -</pre> - -<p>The <code>catch</code> block specifies an identifier (<code>catchID</code> in the preceding syntax) that holds the value specified by the <code>throw</code> statement; you can use this identifier to get information about the exception that was thrown. JavaScript creates this identifier when the <code>catch</code> block is entered; the identifier lasts only for the duration of the <code>catch</code> block; after the <code>catch</code> block finishes executing, the identifier is no longer available.</p> - -<p>For example, the following code throws an exception. When the exception occurs, control transfers to the <code>catch</code> block.</p> - -<pre class="brush: js">try { - throw "myException"; // generates an exception -} -catch (e) { - // statements to handle any exceptions - logMyErrors(e); // pass exception object to error handler -} -</pre> - -<h4 id="The_finally_block">The <code>finally</code> block</h4> - -<p>The <code>finally</code> block contains statements to execute after the <code>try</code> and <code>catch</code> blocks execute but before the statements following the <code>try...catch</code> statement. The <code>finally</code> block executes whether or not an exception is thrown. If an exception is thrown, the statements in the <code>finally</code> block execute even if no <code>catch</code> block handles the exception.</p> - -<p>You can use the <code>finally</code> 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 <code>finally</code> block closes the file before the script fails.</p> - -<pre class="brush: js">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 -} -</pre> - -<p>If the <code>finally</code> block returns a value, this value becomes the return value of the entire <code>try-catch-finally</code> production, regardless of any <code>return</code> statements in the <code>try</code> and <code>catch</code> blocks:</p> - -<pre class="brush: js">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 -</pre> - -<p>Overwriting of return values by the <code>finally</code> block also applies to exceptions thrown or re-thrown inside of the <code>catch</code> block:</p> - -<pre class="brush: js">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"</pre> - -<h4 id="Nesting_try...catch_statements">Nesting try...catch statements</h4> - -<p>You can nest one or more <code>try...catch</code> statements. If an inner <code>try...catch</code> statement does not have a <code>catch</code> block, it needs to have a <code>finally</code> block and the enclosing <code>try...catch</code> statement's <code>catch</code> block is checked for a match. For more information, see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#Nested_try-blocks">nested try-blocks</a> on the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a></code> reference page.</p> - -<h3 id="Utilizing_Error_objects">Utilizing <code>Error</code> objects</h3> - -<p>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.</p> - -<p>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:</p> - -<pre class="brush: js">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) -}</pre> - -<h2 id="Promises">Promises</h2> - -<p>Starting with ECMAScript2015, JavaScript gains support for {{jsxref("Promise")}} objects allowing you to control the flow of deferred and asynchronous operations.</p> - -<p>A <code>Promise</code> is in one of these states:</p> - -<ul> - <li><em>pending</em>: initial state, not fulfilled or rejected.</li> - <li><em>fulfilled</em>: successful operation</li> - <li><em>rejected</em>: failed operation.</li> - <li><em>settled</em>: the Promise is either fulfilled or rejected, but not pending.</li> -</ul> - -<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png" style="height: 297px; width: 801px;"></p> - -<h3 id="Loading_an_image_with_XHR">Loading an image with XHR</h3> - -<p>A simple example using <code>Promise</code> and <code><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> to load an image is available at the MDN GitHub<a href="https://github.com/mdn/promises-test/blob/gh-pages/index.html"> promise-test</a> repository. You can also <a href="http://mdn.github.io/promises-test/">see it in action</a>. Each step is commented and allows you to follow the Promise and XHR architecture closely. Here is the uncommented version, showing the <code>Promise</code> flow so that you can get an idea:</p> - -<pre class="brush: js">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(); - }); -}</pre> - -<p>For more detailed information, see the {{jsxref("Promise")}} reference page.</p> - -<div>{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}</div> 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 ---- -<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}</div> - -<p class="summary">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.</p> - -<p>This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.</p> - -<h2 id="Class-based_vs._prototype-based_languages">Class-based vs. prototype-based languages</h2> - -<p>Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.</p> - -<ul> - <li>A <em>class</em> defines all of the properties that characterize a certain set of objects (considering methods and fields in Java, or members in C++, to be properties). A class is abstract rather than any particular member in a set of objects it describes. For example, the <code>Employee</code> class could represent the set of all employees.</li> - <li>An <em>instance</em>, on the other hand, is the instantiation of a class; that is. For example, <code>Victoria</code> could be an instance of the <code>Employee</code> class, representing a particular individual as an employee. An instance has exactly the same properties of its parent class (no more, no less).</li> -</ul> - -<p>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 <em>prototypical object</em>, 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 <em>prototype</em> for another object, allowing the second object to share the first object's properties.</p> - -<h3 dir="rtl" id="تعریف_یک_کلاس">تعریف یک کلاس</h3> - -<p>In class-based languages, you define a class in a separate <em>class definition</em>. In that definition you can specify special methods, called <em>constructors</em>, 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 <code>new</code> operator in association with the constructor method to create class instances.</p> - -<p>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 <code>new</code> operator with a constructor function to create a new object.</p> - -<div class="blockIndicator note"> -<p>Note that ECMAScript 2015 introduces a <a href="/en-US/docs/Web/JavaScript/Reference/Classes">class declaration</a>:</p> - -<blockquote> -<p>JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax <em>does not</em> introduce a new object-oriented inheritance model to JavaScript.</p> -</blockquote> -</div> - -<h3 id="Subclasses_and_inheritance">Subclasses and inheritance</h3> - -<p>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 <em>subclass</em> 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 <code>Employee</code> class includes only the <code>name</code> and <code>dept</code> properties, and <code>Manager</code> is a subclass of <code>Employee</code> that adds the <code>reports</code> property. In this case, an instance of the <code>Manager</code> class would have all three properties: <code>name</code>, <code>dept</code>, and <code>reports</code>.</p> - -<p>JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the <code>Employee</code> — <code>Manager</code> example, but you use slightly different terminology. First you define the <code>Employee</code> constructor function, specifying the <code>name</code> and <code>dept</code> properties. Next, you define the <code>Manager</code> constructor function, calling the <code>Employee</code> constructor and specifying the <code>reports</code> property. Finally, you assign a new object derived from <code>Employee.prototype</code> as the <code>prototype</code> for the <code>Manager</code> constructor function. Then, when you create a new <code>Manager</code>, it inherits the <code>name</code> and <code>dept</code> properties from the <code>Employee</code> object.</p> - -<h3 id="Adding_and_removing_properties">Adding and removing properties</h3> - -<p>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.</p> - -<h3 id="Summary_of_differences">Summary of differences</h3> - -<p>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.</p> - -<table class="standard-table"> - <caption>Comparison of class-based (Java) and prototype-based (JavaScript) object systems</caption> - <thead> - <tr> - <th scope="row">Category</th> - <th scope="col">Class-based (Java)</th> - <th scope="col">Prototype-based (JavaScript)</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">Class vs. Instance</th> - <td>Class and instance are distinct entities.</td> - <td>All objects can inherit from another object.</td> - </tr> - <tr> - <th scope="row">Definition</th> - <td>Define a class with a class definition; instantiate a class with constructor methods.</td> - <td>Define and create a set of objects with constructor functions.</td> - </tr> - <tr> - <th scope="row">Creation of new object</th> - <td>Create a single object with the <code>new</code> operator.</td> - <td>Same.</td> - </tr> - <tr> - <th scope="row">Construction of object hierarchy</th> - <td>Construct an object hierarchy by using class definitions to define subclasses of existing classes.</td> - <td>Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.</td> - </tr> - <tr> - <th scope="row">Inheritance model</th> - <td>Inherit properties by following the class chain.</td> - <td>Inherit properties by following the prototype chain.</td> - </tr> - <tr> - <th scope="row">Extension of properties</th> - <td>Class definition specifies <em>all</em> properties of all instances of a class. Cannot add properties dynamically at run time.</td> - <td>Constructor function or prototype specifies an <em>initial set</em> of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.</td> - </tr> - </tbody> -</table> - -<h2 id="The_employee_example">The employee example</h2> - -<p>The remainder of this chapter uses the employee hierarchy shown in the following figure.</p> - -<div style="display: table-row;"> -<div style="display: table-cell; width: 350px; text-align: center; vertical-align: middle; padding: 10px;"> -<p>A simple object hierarchy with the following objects:</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/3060/figure8.1.png"></p> -</div> - -<div style="display: table-cell; vertical-align: middle; padding: 10px;"> -<ul> - <li><code>Employee</code> has the properties <code>name</code> (whose value defaults to the empty string) and <code>dept</code> (whose value defaults to "general").</li> - <li><code>Manager</code> is based on <code>Employee</code>. It adds the <code>reports</code> property (whose value defaults to an empty array, intended to have an array of <code>Employee</code> objects as its value).</li> - <li><code>WorkerBee</code> is also based on <code>Employee</code>. It adds the <code>projects</code> property (whose value defaults to an empty array, intended to have an array of strings as its value).</li> - <li><code>SalesPerson</code> is based on <code>WorkerBee</code>. It adds the <code>quota</code> property (whose value defaults to 100). It also overrides the <code>dept</code> property with the value "sales", indicating that all salespersons are in the same department.</li> - <li><code>Engineer</code> is based on <code>WorkerBee</code>. It adds the <code>machine</code> property (whose value defaults to the empty string) and also overrides the <code>dept</code> property with the value "engineering".</li> -</ul> -</div> -</div> - -<h2 id="Creating_the_hierarchy">Creating the hierarchy</h2> - -<p>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.</p> - -<p>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.</p> - -<p>In a real application, you would probably define constructors that allow you to provide property values at object creation time (see <a href="#More_flexible_constructors">More flexible constructors</a> for information). For now, these simple definitions demonstrate how the inheritance occurs.</p> - -<p>The following Java and JavaScript <code>Employee</code> 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 <a href="https://en.wikipedia.org/wiki/Strong_and_weak_typing">strongly typed language</a> while JavaScript is a weakly typed language).</p> - -<h4 id="JavaScript_using_this_may_cause_an_error_for_the_following_examples">JavaScript (using this may cause an error for the following examples)</h4> - -<pre class="brush: js notranslate">class Employee { - constructor() { - this.name = ''; - this.dept = 'general'; - } -} - -</pre> - -<h4 id="JavaScript_**_use_this_instead">JavaScript ** (use this instead)</h4> - -<pre class="brush: js notranslate">function Employee() { - this.name = ''; - this.dept = 'general'; -} - -</pre> - -<h4 id="Java">Java</h4> - -<pre class="brush: java notranslate">public class Employee { - public String name = ""; - public String dept = "general"; -} -</pre> - -<p>The <code>Manager</code> and <code>WorkerBee</code> 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 <code>prototype</code> property of the constructor function, then override the <code>prototype.constructor</code> 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.</p> - -<h4 id="JavaScript">JavaScript</h4> - -<pre class="brush: js notranslate">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; -</pre> - -<h4 id="Java_2">Java</h4> - -<pre class="brush: java notranslate">public class Manager extends Employee { - public Employee[] reports = - new Employee[0]; -} - - - -public class WorkerBee extends Employee { - public String[] projects = new String[0]; -} - - -</pre> - -<p>The <code>Engineer</code> and <code>SalesPerson</code> definitions create objects that descend from <code>WorkerBee</code> and hence from <code>Employee</code>. 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 <code>dept</code> property with new values specific to these objects.</p> - -<h4 id="JavaScript_2">JavaScript</h4> - -<pre class="brush: js notranslate">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; -</pre> - -<h4 id="Java_3">Java</h4> - -<pre class="brush: java notranslate">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 = ""; -} - -</pre> - -<p>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.</p> - -<div class="note"> -<p><strong>Note:</strong> The term <em><em>instance</em></em> 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 <code><code>jane</code></code> is an instance of <code><code>Engineer</code></code>. Similarly, although the terms <em><em>parent</em>, <em>child</em>, <em>ancestor</em></em>, and <em><em>descendant</em></em> do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.</p> -</div> - -<h3 id="Creating_objects_with_simple_definitions">Creating objects with simple definitions</h3> - -<div class="twocolumns"> -<h4 id="Object_hierarchy">Object hierarchy</h4> - -<p>The following hierarchy is created using the code on the right side.</p> - -<p><img src="https://mdn.mozillademos.org/files/10412/=figure8.3.png"></p> - -<h4 id="Individual_objects_Jim_Sally_Mark_Fred_Jane_etc._Instances_created_from_constructor">Individual objects = Jim, Sally, Mark, Fred, Jane, etc.<br> - "Instances" created from constructor</h4> - -<pre class="brush: js notranslate">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 '' -</pre> -</div> - -<h2 id="Object_properties">Object properties</h2> - -<p>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.</p> - -<h3 id="Inheriting_properties">Inheriting properties</h3> - -<p>Suppose you create the <code>mark</code> object as a <code>WorkerBee</code> with the following statement:</p> - -<pre class="brush: js notranslate">var mark = new WorkerBee; -</pre> - -<p>When JavaScript sees the <code>new</code> operator, it creates a new generic object and implicitly sets the value of the internal property [[Prototype]] to the value of <code>WorkerBee.prototype</code> and passes this new object as the value of the <em><code>this</code></em> keyword to the <code>WorkerBee</code> 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 <code>mark</code> to that object.</p> - -<p>This process does not explicitly put values in the <code>mark</code> object (<em>local</em> values) for the properties that <code>mark</code> 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 <code>mark</code> object has the following properties and values:</p> - -<pre class="brush: js notranslate">mark.name = ''; -mark.dept = 'general'; -mark.projects = []; -</pre> - -<p>The <code>mark</code> object is assigned local values for the <code>name</code> and <code>dept</code> properties by the Employee constructor. It is assigned a local value for the <code>projects</code> property by the <code>WorkerBee</code> constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in <a href="#Property_inheritance_revisited">Property inheritance revisited</a>.</p> - -<p>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 <code>WorkerBee</code>. You can, of course, change the values of any of these properties. So, you could give specific information for <code>mark</code> as follows:</p> - -<pre class="brush: js notranslate">mark.name = 'Doe, Mark'; -mark.dept = 'admin'; -mark.projects = ['navigator'];</pre> - -<h3 id="Adding_properties">Adding properties</h3> - -<p>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:</p> - -<pre class="brush: js notranslate">mark.bonus = 3000; -</pre> - -<p>Now, the <code>mark</code> object has a <code>bonus</code> property, but no other <code>WorkerBee</code> has this property.</p> - -<p>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 <code>specialty</code> property to all employees with the following statement:</p> - -<pre class="brush: js notranslate">Employee.prototype.specialty = 'none'; -</pre> - -<p>As soon as JavaScript executes this statement, the <code>mark</code> object also has the <code>specialty</code> property with the value of <code>"none"</code>. The following figure shows the effect of adding this property to the <code>Employee</code> prototype and then overriding it for the <code>Engineer</code> prototype.</p> - -<p><img alt="" class="internal" src="/@api/deki/files/4422/=figure8.4.png" style="height: 519px; width: 833px;"><br> - <small><strong>Adding properties</strong></small></p> - -<h2 id="More_flexible_constructors">More flexible constructors</h2> - -<p>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.</p> - -<p><img alt="" class="internal" id="figure8.5" src="/@api/deki/files/4423/=figure8.5.png" style="height: 481px; width: 1012px;"><br> - <small><strong>Specifying properties in a constructor, take 1</strong></small></p> - -<p>The following pairs of examples show the Java and JavaScript definitions for these objects.</p> - -<pre class="brush: js notranslate">function Employee(name, dept) { - this.name = name || ''; - this.dept = dept || 'general'; -} -</pre> - -<pre class="brush: java notranslate">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; - } -} -</pre> - -<pre class="brush: js notranslate">function WorkerBee(projs) { - this.projects = projs || []; -} -WorkerBee.prototype = new Employee; -</pre> - -<pre class="brush: java notranslate">public class WorkerBee extends Employee { - public String[] projects; - public WorkerBee () { - this(new String[0]); - } - public WorkerBee (String[] projs) { - projects = projs; - } -} -</pre> - -<pre class="brush: js notranslate"> -function Engineer(mach) { - this.dept = 'engineering'; - this.machine = mach || ''; -} -Engineer.prototype = new WorkerBee; -</pre> - -<pre class="brush: java notranslate">public class Engineer extends WorkerBee { - public String machine; - public Engineer () { - dept = "engineering"; - machine = ""; - } - public Engineer (String mach) { - dept = "engineering"; - machine = mach; - } -} -</pre> - -<p>These JavaScript definitions use a special idiom for setting default values:</p> - -<pre class="brush: js notranslate">this.name = name || ''; -</pre> - -<p>The JavaScript logical OR operator (<code>||</code>) 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 <code>name</code> has a useful value for the <code>name</code> property. If it does, it sets <code>this.name</code> to that value. Otherwise, it sets <code>this.name</code> to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.</p> - -<div class="note"> -<p><strong>Note:</strong> This may not work as expected if the constructor function is called with arguments which convert to <code><code>false</code></code> (like <code>0</code> (zero) and empty string (<code><code>""</code></code>). In this case the default value will be chosen.</p> -</div> - -<p>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 <code>Engineer</code>:</p> - -<pre class="brush: js notranslate">var jane = new Engineer('belau'); -</pre> - -<p><code>Jane</code>'s properties are now:</p> - -<pre class="brush: js notranslate">jane.name == ''; -jane.dept == 'engineering'; -jane.projects == []; -jane.machine == 'belau'; -</pre> - -<p>Notice that with these definitions, you cannot specify an initial value for an inherited property such as <code>name</code>. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.</p> - -<p>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.</p> - -<p><img alt="" class="internal" src="/@api/deki/files/4430/=figure8.6.png" style="height: 534px; width: 1063px;"><br> - <small><strong>Specifying properties in a constructor, take 2</strong></small></p> - -<p>Let's look at one of these definitions in detail. Here's the new definition for the <code>Engineer</code> constructor:</p> - -<pre class="brush: js notranslate">function Engineer(name, projs, mach) { - this.base = WorkerBee; - this.base(name, 'engineering', projs); - this.machine = mach || ''; -} -</pre> - -<p>Suppose you create a new <code>Engineer</code> object as follows:</p> - -<pre class="brush: js notranslate">var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau'); -</pre> - -<p>JavaScript follows these steps:</p> - -<ol> - <li>The <code>new</code> operator creates a generic object and sets its <code>__proto__</code> property to <code>Engineer.prototype</code>.</li> - <li>The <code>new</code> operator passes the new object to the <code>Engineer</code> constructor as the value of the <code>this</code> keyword.</li> - <li>The constructor creates a new property called <code>base</code> for that object and assigns the value of the <code>WorkerBee</code> constructor to the <code>base</code> property. This makes the <code>WorkerBee</code> constructor a method of the <code>Engineer</code> object. The name of the <code>base</code> property is not special. You can use any legal property name; <code>base</code> is simply evocative of its purpose.</li> - <li>The constructor calls the <code>base</code> method, passing as its arguments two of the arguments passed to the constructor (<code>"Doe, Jane"</code> and <code>["navigator", "javascript"]</code>) and also the string <code>"engineering"</code>. Explicitly using <code>"engineering"</code> in the constructor indicates that all <code>Engineer</code> objects have the same value for the inherited <code>dept</code> property, and this value overrides the value inherited from <code>Employee</code>.</li> - <li>Because <code>base</code> is a method of <code>Engineer</code>, within the call to <code>base</code>, JavaScript binds the <code>this</code> keyword to the object created in Step 1. Thus, the <code>WorkerBee</code> function in turn passes the <code>"Doe, Jane"</code> and <code>"engineering"</code> arguments to the <code>Employee</code> constructor function. Upon return from the <code>Employee</code> constructor function, the <code>WorkerBee</code> function uses the remaining argument to set the <code>projects</code> property.</li> - <li>Upon return from the <code>base</code> method, the <code>Engineer</code> constructor initializes the object's <code>machine</code> property to <code>"belau"</code>.</li> - <li>Upon return from the constructor, JavaScript assigns the new object to the <code>jane</code> variable.</li> -</ol> - -<p>You might think that, having called the <code>WorkerBee</code> constructor from inside the <code>Engineer</code> constructor, you have set up inheritance appropriately for <code>Engineer</code> objects. This is not the case. Calling the <code>WorkerBee</code> constructor ensures that an <code>Engineer</code> object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the <code>Employee</code> or <code>WorkerBee</code> prototypes, those properties are not inherited by the <code>Engineer</code> object. For example, assume you have the following statements:</p> - -<pre class="brush: js notranslate">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'; -</pre> - -<p>The <code>jane</code> object does not inherit the <code>specialty</code> property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:</p> - -<pre class="brush: js notranslate">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'; -</pre> - -<p>Now the value of the <code>jane</code> object's <code>specialty</code> property is "none".</p> - -<p>Another way of inheriting is by using the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global Objects/Function/call">call()</a></code> / <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="en-US/docs/JavaScript/Reference/Global Objects/Function/apply"><code>apply()</code></a> methods. Below are equivalent:</p> - -<pre class="brush: js notranslate">function Engineer(name, projs, mach) { - this.base = WorkerBee; - this.base(name, 'engineering', projs); - this.machine = mach || ''; -} -</pre> - -<pre class="brush: js notranslate">function Engineer(name, projs, mach) { - WorkerBee.call(this, name, 'engineering', projs); - this.machine = mach || ''; -} -</pre> - -<p>Using the javascript <code>call()</code> method makes a cleaner implementation because the <code>base</code> is not needed anymore.</p> - -<h2 id="Property_inheritance_revisited">Property inheritance revisited</h2> - -<p>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.</p> - -<h3 id="Local_versus_inherited_values">Local versus inherited values</h3> - -<p>When you access an object property, JavaScript performs these steps, as described earlier in this chapter:</p> - -<ol> - <li>Check to see if the value exists locally. If it does, return that value.</li> - <li>If there is not a local value, check the prototype chain (using the <code>__proto__</code> property).</li> - <li>If an object in the prototype chain has a value for the specified property, return that value.</li> - <li>If no such property is found, the object does not have the property.</li> -</ol> - -<p>The outcome of these steps depends on how you define things along the way. The original example had these definitions:</p> - -<pre class="brush: js notranslate">function Employee() { - this.name = ''; - this.dept = 'general'; -} - -function WorkerBee() { - this.projects = []; -} -WorkerBee.prototype = new Employee; -</pre> - -<p>With these definitions, suppose you create <code>amy</code> as an instance of <code>WorkerBee</code> with the following statement:</p> - -<pre class="brush: js notranslate">var amy = new WorkerBee; -</pre> - -<p>The <code>amy</code> object has one local property, <code>projects</code>. The values for the <code>name</code> and <code>dept</code> properties are not local to <code>amy</code> and so derive from the <code>amy</code> object's <code>__proto__</code> property. Thus, <code>amy</code> has these property values:</p> - -<pre class="brush: js notranslate">amy.name == ''; -amy.dept == 'general'; -amy.projects == []; -</pre> - -<p>Now suppose you change the value of the <code>name</code> property in the prototype associated with <code>Employee</code>:</p> - -<pre class="brush: js notranslate">Employee.prototype.name = 'Unknown'; -</pre> - -<p>At first glance, you might expect that new value to propagate down to all the instances of <code>Employee</code>. However, it does not.</p> - -<p>When you create <em>any</em> instance of the <code>Employee</code> object, that instance gets a <strong>local value</strong> for the <code>name</code> property (the empty string). This means that when you set the <code>WorkerBee</code> prototype by creating a new <code>Employee</code> object, <code>WorkerBee.prototype</code> has a local value for the <code>name</code> property. Therefore, when JavaScript looks up the <code>name</code> property of the <code>amy</code> object (an instance of <code>WorkerBee</code>), JavaScript finds the local value for that property in <code>WorkerBee.prototype</code>. It therefore does not look further up the chain to <code>Employee.prototype</code>.</p> - -<p>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:</p> - -<pre class="brush: js notranslate">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'; -</pre> - -<p>In this case, the <code>name</code> property of <code>amy</code> becomes "Unknown".</p> - -<p>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.</p> - -<h3 id="Determining_instance_relationships">Determining instance relationships</h3> - -<p>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 <code>__proto__</code>. This continues recursively; the process is called "lookup in the prototype chain".</p> - -<p>The special property <code>__proto__</code> is set when an object is constructed; it is set to the value of the constructor's <code>prototype</code> property. So the expression <code>new Foo()</code> creates an object with <code>__proto__ == <code class="moz-txt-verticalline">Foo.prototype</code></code>. Consequently, changes to the properties of <code class="moz-txt-verticalline">Foo.prototype</code> alters the property lookup for all objects that were created by <code>new Foo()</code>.</p> - -<p>Every object has a <code>__proto__</code> object property (except <code>Object</code>); every function has a <code>prototype</code> object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's <code>__proto__</code> to a function's <code>prototype</code> object. JavaScript provides a shortcut: the <code>instanceof</code> operator tests an object against a function and returns true if the object inherits from the function prototype. For example,</p> - -<pre class="brush: js notranslate">var f = new Foo(); -var isTrue = (f instanceof Foo);</pre> - -<p>For a more detailed example, suppose you have the same set of definitions shown in <a href="#Inheriting_properties">Inheriting properties</a>. Create an <code>Engineer</code> object as follows:</p> - -<pre class="brush: js notranslate">var chris = new Engineer('Pigman, Chris', ['jsd'], 'fiji'); -</pre> - -<p>With this object, the following statements are all true:</p> - -<pre class="brush: js notranslate">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; -</pre> - -<p>Given this, you could write an <code>instanceOf</code> function as follows:</p> - -<pre class="brush: js notranslate">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; -} -</pre> - -<div class="note"><strong>Note:</strong> 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 <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=634150">bug 634150</a> if you want the nitty-gritty details.</div> - -<p>Using the instanceOf function defined above, these expressions are true:</p> - -<pre class="brush: js notranslate">instanceOf(chris, Engineer) -instanceOf(chris, WorkerBee) -instanceOf(chris, Employee) -instanceOf(chris, Object) -</pre> - -<p>But the following expression is false:</p> - -<pre class="brush: js notranslate">instanceOf(chris, SalesPerson) -</pre> - -<h3 id="Global_information_in_constructors">Global information in constructors</h3> - -<p>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 <code>Employee</code>:</p> - -<pre class="brush: js notranslate">var idCounter = 1; - -function Employee(name, dept) { - this.name = name || ''; - this.dept = dept || 'general'; - this.id = idCounter++; -} -</pre> - -<p>With this definition, when you create a new <code>Employee</code>, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, <code>victoria.id</code> is 1 and <code>harry.id</code> is 2:</p> - -<pre class="brush: js notranslate">var victoria = new Employee('Pigbert, Victoria', 'pubs'); -var harry = new Employee('Tschopik, Harry', 'sales'); -</pre> - -<p>At first glance that seems fine. However, <code>idCounter</code> gets incremented every time an <code>Employee</code> object is created, for whatever purpose. If you create the entire <code>Employee</code> hierarchy shown in this chapter, the <code>Employee</code> constructor is called every time you set up a prototype. Suppose you have the following code:</p> - -<pre class="brush: js notranslate">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'); -</pre> - -<p>Further assume that the definitions omitted here have the <code>base</code> property and call the constructor above them in the prototype chain. In this case, by the time the <code>mac</code> object is created, <code>mac.id</code> is 5.</p> - -<p>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:</p> - -<pre class="brush: js notranslate">function Employee(name, dept) { - this.name = name || ''; - this.dept = dept || 'general'; - if (name) - this.id = idCounter++; -} -</pre> - -<p>When you create an instance of <code>Employee</code> 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 <code>Employee</code> to get an assigned id, you must specify a name for the employee. In this example, <code>mac.id</code> would be 1.</p> - -<p>Alternatively, you can create a copy of Employee's prototype object to assign to WorkerBee:</p> - -<pre class="brush: js notranslate">WorkerBee.prototype = Object.create(Employee.prototype); -// instead of WorkerBee.prototype = new Employee -</pre> - -<h3 id="No_multiple_inheritance">No multiple inheritance</h3> - -<p>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.</p> - -<p>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.</p> - -<p>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:</p> - -<pre class="brush: js notranslate">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'); -</pre> - -<p>Further assume that the definition of <code>WorkerBee</code> is as used earlier in this chapter. In this case, the <code>dennis</code> object has these properties:</p> - -<pre class="brush: js notranslate">dennis.name == 'Doe, Dennis'; -dennis.dept == 'engineering'; -dennis.projects == ['collabra']; -dennis.machine == 'hugo'; -dennis.hobby == 'scuba'; -</pre> - -<p>So <code>dennis</code> does get the <code>hobby</code> property from the <code>Hobbyist</code> constructor. However, assume you then add a property to the <code>Hobbyist</code> constructor's prototype:</p> - -<pre class="brush: js notranslate">Hobbyist.prototype.equipment = ['mask', 'fins', 'regulator', 'bcd']; -</pre> - -<p>The <code>dennis</code> object does not inherit this new property.</p> - -<div>{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}</div> 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 ---- -<div dir="rtl">{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</div> - -<p class="summary">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.</p> - -<p>See also the <a href="/en-US/docs/Web/JavaScript/Reference/Functions">exhaustive reference chapter about JavaScript functions</a> to get to know the details.</p> - -<h2 id="Defining_functions">Defining functions</h2> - -<h3 id="Function_declarations">Function declarations</h3> - -<p>A <strong>function definition</strong> (also called a <strong>function declaration</strong>, or <strong>function statement</strong>) consists of the <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function" title="function"><code>function</code></a> keyword, followed by:</p> - -<ul> - <li>The name of the function.</li> - <li>A list of parameters to the function, enclosed in parentheses and separated by commas.</li> - <li>The JavaScript statements that define the function, enclosed in curly brackets, <code>{ }</code>.</li> -</ul> - -<p>For example, the following code defines a simple function named <code> square</code>:</p> - -<pre class="brush: js">function square(number) { - return number * number; -} -</pre> - -<p>The function <code>square</code> takes one parameter, called <code>number</code>. The function consists of one statement that says to return the parameter of the function (that is, <code>number</code>) multiplied by itself. The <a href="/en-US/docs/Web/JavaScript/Reference/Statements/return" title="return"><code>return</code></a> statement specifies the value returned by the function.</p> - -<pre class="brush: js">return number * number; -</pre> - -<p>Primitive parameters (such as a number) are passed to functions <strong>by value</strong>; 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.</p> - -<p>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:</p> - -<pre class="brush: js">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) -</pre> - -<h3 id="Function_expressions">Function expressions</h3> - -<p>While the function declaration above is syntactically a statement, functions can also be created by a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a>. Such a function can be <strong>anonymous</strong>; it does not have to have a name. For example, the function <code>square</code> could have been defined as:</p> - -<pre class="brush: js">var square = function(number) { return number * number; }; -var x = square(4); // x gets the value 16</pre> - -<p>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:</p> - -<pre class="brush: js">var factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); }; - -console.log(factorial(3)); -</pre> - -<p>Function expressions are convenient when passing a function as an argument to another function. The following example shows a <code>map</code> function being defined and then called with an expression function as its first parameter:</p> - -<pre class="brush: js">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; -} -</pre> - -<p>The following code:</p> - -<pre class="brush: js">var numbers = [0,1, 2, 5,10]; -var cube= numbers.map(function(x) { - return x * x * x; -}); -console.log(cube);</pre> - -<p>returns [0, 1, 8, 125, 1000].</p> - -<p>In JavaScript, a function can be defined based on a condition. For example, the following function definition defines <code>myFunc</code> only if <code>num</code> equals 0:</p> - -<pre class="brush: js">var myFunc; -if (num === 0) { - myFunc = function(theObject) { - theObject.make = 'Toyota'; - } -}</pre> - -<p>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()")}}.</p> - -<p>A <strong>method</strong> is a function that is a property of an object. Read more about objects and methods in <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects" title="en-US/docs/JavaScript/Guide/Working with Objects">Working with objects</a>.</p> - -<h2 id="Calling_functions">Calling functions</h2> - -<p>Defining a function does not execute it. Defining the function simply names the function and specifies what to do when the function is called. <strong>Calling</strong> the function actually performs the specified actions with the indicated parameters. For example, if you define the function <code>square</code>, you could call it as follows:</p> - -<pre class="brush: js">square(5); -</pre> - -<p>The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25.</p> - -<p>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:</p> - -<pre class="brush: js">console.log(square(5)); -/* ... */ -function square(n) { return n * n; } -</pre> - -<p>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.</p> - -<div class="note"> -<p><strong>Note:</strong> This works only when defining the function using the above syntax (i.e. <code>function funcName(){}</code>). The code below will not work. That means, function hoisting only works with function declaration and not with function expression.</p> -</div> - -<pre class="brush: js example-bad">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; -} -</pre> - -<p>The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The <code>show_props()</code> function (defined in <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_Properties" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects#Objects_and_Properties">Working with objects</a>) is an example of a function that takes an object as an argument.</p> - -<p>A function can call itself. For example, here is a function that computes factorials recursively:</p> - -<pre class="brush: js">function factorial(n) { - if ((n === 0) || (n === 1)) - return 1; - else - return (n * factorial(n - 1)); -} -</pre> - -<p>You could then compute the factorials of one through five as follows:</p> - -<pre class="brush: js">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 -</pre> - -<p>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.</p> - -<h2 class="deki-transform" id="Function_scope">Function scope</h2> - -<p>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.</p> - -<pre class="brush: js">// 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" -</pre> - -<h2 id="Scope_and_the_function_stack">Scope and the function stack</h2> - -<h3 id="Recursion">Recursion</h3> - -<p>A function can refer to and call itself. There are three ways for a function to refer to itself:</p> - -<ol> - <li>the function's name</li> - <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee</a></code></li> - <li>an in-scope variable that refers to the function</li> -</ol> - -<p>For example, consider the following function definition:</p> - -<pre class="brush: js">var foo = function bar() { - // statements go here -}; -</pre> - -<p>Within the function body, the following are all equivalent:</p> - -<ol> - <li><code>bar()</code></li> - <li><code>arguments.callee()</code></li> - <li><code>foo()</code></li> -</ol> - -<p>A function that calls itself is called a <em>recursive function</em>. 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:</p> - -<pre class="brush: js">var x = 0; -while (x < 10) { // "x < 10" is the loop condition - // do stuff - x++; -} -</pre> - -<p>can be converted into a recursive function and a call to that function:</p> - -<pre class="brush: js">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); -</pre> - -<p>However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the <a href="/en-US/docs/DOM">DOM</a>) is more easily done using recursion:</p> - -<pre class="brush: js">function walkTree(node) { - if (node == null) // - return; - // do something with node - for (var i = 0; i < node.childNodes.length; i++) { - walkTree(node.childNodes[i]); - } -} -</pre> - -<p>Compared to the function <code>loop</code>, each recursive call itself makes many recursive calls here.</p> - -<p>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.</p> - -<p>The stack-like behavior can be seen in the following example:</p> - -<pre class="brush: js">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</pre> - -<h3 id="Nested_functions_and_closures">Nested functions and closures</h3> - -<p>You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a <em>closure</em>. 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).</p> - -<p>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.</p> - -<p>To summarize:</p> - -<ul> - <li>The inner function can be accessed only from statements in the outer function.</li> -</ul> - -<ul> - <li>The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.</li> -</ul> - -<p>The following example shows nested functions:</p> - -<pre class="brush: js">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 -</pre> - -<p>Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:</p> - -<pre class="brush: js">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 -</pre> - -<h3 id="Preservation_of_variables">Preservation of variables</h3> - -<p>Notice how <code>x</code> is preserved when <code>inside</code> 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 <code>inside</code> is no longer accessible.</p> - -<p>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.</p> - -<h3 id="Multiply-nested_functions">Multiply-nested functions</h3> - -<p>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 <em>scope chaining</em>. (Why it is called "chaining" will be explained later.)</p> - -<p>Consider the following example:</p> - -<pre class="brush: js">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) -</pre> - -<p>In this example, <code>C</code> accesses <code>B</code>'s <code>y</code> and <code>A</code>'s <code>x</code>. This can be done because:</p> - -<ol> - <li><code>B</code> forms a closure including <code>A</code>, i.e. <code>B</code> can access <code>A</code>'s arguments and variables.</li> - <li><code>C</code> forms a closure including <code>B</code>.</li> - <li>Because <code>B</code>'s closure includes <code>A</code>, <code>C</code>'s closure includes <code>A</code>, <code>C</code> can access both <code>B</code> <em>and</em> <code>A</code>'s arguments and variables. In other words, <code>C</code> <em>chains</em> the scopes of <code>B</code> and <code>A</code> in that order.</li> -</ol> - -<p>The reverse, however, is not true. <code>A</code> cannot access <code>C</code>, because <code>A</code> cannot access any argument or variable of <code>B</code>, which <code>C</code> is a variable of. Thus, <code>C</code> remains private to only <code>B</code>.</p> - -<h3 id="Name_conflicts">Name conflicts</h3> - -<p>When two arguments or variables in the scopes of a closure have the same name, there is a <em>name conflict</em>. 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:</p> - -<pre class="brush: js">function outside() { - var x = 5; - function inside(x) { - return x * 2; - } - return inside; -} - -outside()(10); // returns 20 instead of 10 -</pre> - -<p>The name conflict happens at the statement <code>return x</code> and is between <code>inside</code>'s parameter <code>x</code> and <code>outside</code>'s variable <code>x</code>. The scope chain here is {<code>inside</code>, <code>outside</code>, global object}. Therefore <code>inside</code>'s <code>x</code> takes precedences over <code>outside</code>'s <code>x</code>, and 20 (<code>inside</code>'s <code>x</code>) is returned instead of 10 (<code>outside</code>'s <code>x</code>).</p> - -<h2 id="Closures">Closures</h2> - -<p>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.</p> - -<pre class="brush: js">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" -</pre> - -<p>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.</p> - -<pre class="brush: js">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 -</pre> - -<p>In the code above, the <code>name</code> 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.</p> - -<pre class="brush: js">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 -</pre> - -<p>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.</p> - -<pre class="brush: js">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 ??? - } - } -} -</pre> - -<h2 id="Using_the_arguments_object">Using the arguments object</h2> - -<p>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:</p> - -<pre class="brush: js">arguments[i] -</pre> - -<p>where <code>i</code> is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be <code>arguments[0]</code>. The total number of arguments is indicated by <code>arguments.length</code>.</p> - -<p>Using the <code>arguments</code> 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 <code>arguments.length</code> to determine the number of arguments actually passed to the function, and then access each argument using the <code>arguments</code> object.</p> - -<p>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:</p> - -<pre class="brush: js">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; -} -</pre> - -<p>You can pass any number of arguments to this function, and it concatenates each argument into a string "list":</p> - -<pre class="brush: js">// 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'); -</pre> - -<div class="note"> -<p><strong>Note:</strong> The <code>arguments</code> variable is "array-like", but not an array. It is array-like in that it has a numbered index and a <code>length</code> property. However, it does not possess all of the array-manipulation methods.</p> -</div> - -<p>See the {{jsxref("Function")}} object in the JavaScript reference for more information.</p> - -<h2 id="Function_parameters">Function parameters</h2> - -<p>Starting with ECMAScript 2015, there are two new kinds of parameters: default parameters and rest parameters.</p> - -<h3 id="Default_parameters">Default parameters</h3> - -<p>In JavaScript, parameters of functions default to <code>undefined</code>. However, in some situations it might be useful to set a different default value. This is where default parameters can help.</p> - -<p>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 <code>undefined</code>. If in the following example, no value is provided for <code>b</code> in the call, its value would be <code>undefined</code> when evaluating <code>a*b</code> and the call to <code>multiply</code> would have returned <code>NaN</code>. However, this is caught with the second line in this example:</p> - -<pre class="brush: js">function multiply(a, b) { - b = typeof b !== 'undefined' ? b : 1; - - return a * b; -} - -multiply(5); // 5 -</pre> - -<p>With default parameters, the check in the function body is no longer necessary. Now, you can simply put <code>1</code> as the default value for <code>b</code> in the function head:</p> - -<pre class="brush: js">function multiply(a, b = 1) { - return a * b; -} - -multiply(5); // 5</pre> - -<p>For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a> in the reference.</p> - -<h3 id="Rest_parameters">Rest parameters</h3> - -<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameter</a> 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.</p> - -<pre class="brush: js">function multiply(multiplier, ...theArgs) { - return theArgs.map(x => multiplier * x); -} - -var arr = multiply(2, 1, 2, 3); -console.log(arr); // [2, 4, 6]</pre> - -<h2 id="Arrow_functions">Arrow functions</h2> - -<p>An <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> (previously, and now incorrectly known as <strong>fat arrow function</strong>) has a shorter syntax compared to function expressions and lexically binds the <code>this</code> value. Arrow functions are always anonymous. See also this hacks.mozilla.org blog post: "<a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">ES6 In Depth: Arrow functions</a>".</p> - -<p>Two factors influenced the introduction of arrow functions: shorter functions and lexical <code>this</code>.</p> - -<h3 id="Shorter_functions">Shorter functions</h3> - -<p>In some functional patterns, shorter functions are welcome. Compare:</p> - -<pre class="brush: js">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] -</pre> - -<h3 id="Lexical_this">Lexical <code>this</code></h3> - -<p>Until arrow functions, every new function defined its own <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a> 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.</p> - -<pre class="brush: js">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();</pre> - -<p>In ECMAScript 3/5, this issue was fixed by assigning the value in <code>this</code> to a variable that could be closed over.</p> - -<pre class="brush: js">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); -}</pre> - -<p>Alternatively, a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bound function</a> could be created so that the proper <code>this</code> value would be passed to the <code>growUp()</code> function.</p> - -<p>Arrow functions capture the <code>this</code> value of the enclosing context, so the following code works as expected.</p> - -<pre class="brush: js">function Person() { - this.age = 0; - - setInterval(() => { - this.age++; // |this| properly refers to the person object - }, 1000); -} - -var p = new Person();</pre> - -<h2 id="Predefined_functions">Predefined functions</h2> - -<p>JavaScript has several top-level, built-in functions:</p> - -<dl> - <dt>{{jsxref("Global_Objects/eval", "eval()")}}</dt> - <dd> - <p>The <code><strong>eval()</strong></code> method evaluates JavaScript code represented as a string.</p> - </dd> - <dt>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}</dt> - <dd> - <p>The <code><strong>uneval()</strong></code> method creates a string representation of the source code of an {{jsxref("Object")}}.</p> - </dd> - <dt>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</dt> - <dd> - <p>The global <code><strong>isFinite()</strong></code> function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.</p> - </dd> - <dt>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</dt> - <dd> - <p>The <code><strong>isNaN()</strong></code> function determines whether a value is {{jsxref("Global_Objects/NaN", "NaN")}} or not. Note: coercion inside the <code>isNaN</code> function has <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description">interesting</a> rules; you may alternatively want to use {{jsxref("Number.isNaN()")}}, as defined in ECMAScript 2015, or you can use <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></code> to determine if the value is Not-A-Number.</p> - </dd> - <dt>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</dt> - <dd> - <p>The <code><strong>parseFloat()</strong></code> function parses a string argument and returns a floating point number.</p> - </dd> - <dt>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</dt> - <dd> - <p>The <code><strong>parseInt()</strong></code> function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).</p> - </dd> - <dt>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</dt> - <dd> - <p>The <code><strong>decodeURI()</strong></code> function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or by a similar routine.</p> - </dd> - <dt>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</dt> - <dd> - <p>The <code><strong>decodeURIComponent()</strong></code> method decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} or by a similar routine.</p> - </dd> - <dt>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</dt> - <dd> - <p>The <code><strong>encodeURI()</strong></code> 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).</p> - </dd> - <dt>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</dt> - <dd> - <p>The <code><strong>encodeURIComponent()</strong></code> 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).</p> - </dd> - <dt>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}</dt> - <dd> - <p>The deprecated <code><strong>escape()</strong></code> 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.</p> - </dd> - <dt>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}</dt> - <dd> - <p>The deprecated <code><strong>unescape()</strong></code> 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 <code>unescape()</code> is deprecated, use {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} instead.</p> - </dd> -</dl> - -<p>{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</p> 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 ---- -<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</div> - -<p class="summary" dir="rtl">این فصل در مورد گرامر اولیه جاوااسکریپت، اعلانهای متغیر، انواع داده و لیترالها است.</p> - -<h2 dir="rtl" id="مقدمه">مقدمه</h2> - -<p dir="rtl">جاوااسکریپت قسمت زیادی از نحو خود را از جاوا اقتباس کرده و همچنین از زبانهای پرل، پایتون و Awk تاثیر گرفته است.</p> - -<p dir="rtl">جاوااسکریپت <strong>حساس به</strong> <strong>کوچکی و بزرگی حروف (case-sensetive)</strong> است و از مجموعه کاراکترهای <strong>یونیکد (Unicode)</strong> استفاده میکند.</p> - -<p>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 (<a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">ASI</a>) 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 <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">lexical grammar</a>.</p> - -<h2 dir="rtl" id="توضیح_(comment)">توضیح (comment)</h2> - -<p dir="rtl">نحو (syntax) یک «توضیح» مشابه با زبان C++ و تعداد زیادی از زبانهای دیگر است.<br> - مثال اول: توضیح تکخطی<br> - مثال دوم: توضیح چندخطی (بلوک)<br> - مثال سوم: اگرچه، برخلاف c++ نمیتوان توضیح تو در تو ساخت. احتمالا خطای نحوی خواهد بود.</p> - -<pre class="brush: js">// a one line comment - -/* this is a longer, - multi-line comment - */ - -/* You can't, however, /* nest comments */ SyntaxError */</pre> - -<h2 dir="rtl" id="اعلانها_(Declarations)">اعلانها (Declarations)</h2> - -<p dir="rtl">سه نوع اعلان در جاوااسکریپت وجود دارد.</p> - -<dl> - <dt dir="rtl">{{jsxref("Statements/var", "var")}}</dt> - <dd dir="rtl">یک متغیر را اعلان میکند. مقداردهی اولیه اختیاری است.</dd> - <dt dir="rtl">{{jsxref("Statements/let", "let")}}</dt> - <dd dir="rtl">یک متغیر محلی را با قلمرو بلوک اعلان میکند. مقداردهی اولیه اختیاری است.</dd> - <dt dir="rtl">{{jsxref("Statements/const", "const")}}</dt> - <dd dir="rtl">یک ثابت «فقط خواندنی» را اعلان میکند.</dd> -</dl> - -<h3 dir="rtl" id="متغیرها">متغیرها</h3> - -<p dir="rtl">You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.</p> - -<p dir="rtl">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).</p> - -<p dir="rtl">You can use most of ISO 8859-1 or Unicode letters such as å and ü in identifiers (for more details see <a href="https://mathiasbynens.be/notes/javascript-identifiers-es6">this blog post</a>). You can also use the <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a> as characters in identifiers.</p> - -<p dir="rtl">نامهای روبرو مثالهایی معتبر برای نامگذاری هستند: <code>Number_hits</code>, <code>temp99</code>, <code>_name</code></p> - -<h3 dir="rtl" id="اعلان_متغیرها">اعلان متغیرها</h3> - -<p dir="rtl">شما به سه روش میتوانید یک متغیر را اعلان کنید:</p> - -<ul dir="rtl"> - <li>با کلمهکلیدی {{jsxref("Statements/var", "var")}}. برای مثال <code>var x = 42</code>. این نحو میتواند برای اعلان هر دو نوع متغیر محلی و سراسری استفاده شود.</li> - <li>به سادگی و با انتساب یک مقدار به آن. برای مثال <code>x = 42</code>. این شیوه همیشه یک متغیر را به صورت سراسری اعلان میکند. این روش یک هشدار سختگیرانه (strict warning) تولید میکند. بهتر است از این روش استفاده نکنید.</li> - <li>با کلمهکلیدی {{jsxref("Statements/let", "let")}}. برای مثال <code>let y = 13</code>. این نحو میتواند برای اعلان یک متغیر محلی با قلمرو بلوک استفاده شود. بخش <a href="#قلمرو_متغیر_(Variable_Scope)">قلمرو متغیر</a> را در زیر ببینید.</li> -</ul> - -<h3 dir="rtl" id="ارزیابی_متغیرها">ارزیابی متغیرها</h3> - -<p dir="rtl">A variable declared using the <code>var or let</code> statement with no initial value specified has the value {{jsxref("undefined")}}.</p> - -<p dir="rtl">An attempt to access an undeclared variable will result in a {{jsxref("ReferenceError")}} exception being thrown:</p> - -<pre dir="rtl">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; </pre> - -<p dir="rtl">شما میتوانید از <code>undefined</code> برای مشخص کردن اینکه آیا یک متغیر دارای مقدار است استفاده کنید. در کد زیر به متغیر <code>input</code> مقداری انتساب داده نشده است و عبارت منطقی <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if</a></code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else"> </a>برابر با <code>true</code> ارزیابی میشود.</p> - -<pre class="brush: js" dir="rtl">var input; -if(input === undefined){ - doThis(); -} else { - doThat(); -} -</pre> - -<p dir="rtl">رفتار مقدار <code>undefined</code> در ارزیابی عبارات منطقی مانند <code>false</code> است. برای مثال، در کد زیر تابع <code>myFunction</code> اجرا خواهد شد چون المان <code>myArray</code> تعریفنشده است:</p> - -<pre class="brush: js" dir="rtl">var myArray = []; -if (!myArray[0]) myFunction(); -</pre> - -<p dir="rtl">در یک عبارت عددی مقدار <code>undefined</code> به <code>NaN</code> تبدیل میشود.</p> - -<pre class="brush: js" dir="rtl">var a; -a + 2; // Evaluates to NaN</pre> - -<p dir="rtl">وقتی یک متغیر {{jsxref("null")}} را ارزیابی میکنید، در یک عبارت عددی دارای مقدارصفر و در یک عبارت منطقی دارای مقدار <code>false</code> خواهد بود. برای مثال:</p> - -<pre class="brush: js" dir="rtl">var n = null; -console.log(n * 32); // Will log 0 to the console -</pre> - -<h3 dir="rtl" id="قلمرو_متغیر_(Variable_Scope)">قلمرو متغیر (Variable Scope)</h3> - -<p dir="rtl">When you declare a variable outside of any function, it is called a <em>global</em> 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 <em>local</em> variable, because it is available only within that function.</p> - -<p dir="rtl">JavaScript before ECMAScript 2015 does not have <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement">block statement</a> scope; rather, a variable declared within a block is local to the <em>function (or global scope)</em> that the block resides within. For example the following code will log <code>5</code>, because the scope of <code>x</code> is the function (or global context) within which <code>x</code> is declared, not the block, which in this case is an <code>if</code> statement.</p> - -<pre class="brush: js" dir="rtl">if (true) { - var x = 5; -} -console.log(x); // x is 5 -</pre> - -<p dir="rtl">This behavior changes, when using the <code>let</code> declaration introduced in ECMAScript 2015.</p> - -<pre class="brush: js" dir="rtl">if (true) { - let y = 5; -} -console.log(y); // ReferenceError: y is not defined -</pre> - -<h3 dir="rtl" id="Variable_hoisting">Variable hoisting</h3> - -<p dir="rtl">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 <strong>hoisting</strong>; 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 <code>undefined</code>. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.</p> - -<pre class="brush: js" dir="rtl">/** - * 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"; -})(); -</pre> - -<p dir="rtl">The above examples will be interpreted the same as:</p> - -<pre class="brush: js" dir="rtl">/** - * 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"; -})(); -</pre> - -<p dir="rtl">Because of hoisting, all <code>var</code> 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.</p> - -<p dir="rtl">In ECMAScript 2015, <code>let (const)</code> <strong>will not hoist</strong> 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.</p> - -<pre class="brush: js" dir="rtl">console.log(x); // ReferenceError -let x = 3;</pre> - -<h3 dir="rtl" id="Function_hoisting">Function hoisting</h3> - -<p dir="rtl">For functions, only function declaration gets hoisted to the top and not the function expression.</p> - -<pre class="brush: js" dir="rtl">/* Function declaration */ - -foo(); // "bar" - -function foo() { - console.log("bar"); -} - - -/* Function expression */ - -baz(); // TypeError: baz is not a function - -var baz = function() { - console.log("bar2"); -}; -</pre> - -<h3 dir="rtl" id="Global_variables">Global variables</h3> - -<p dir="rtl">Global variables are in fact properties of the <em>global object</em>. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the <code>window.<em>variable</em></code> syntax.</p> - -<p dir="rtl">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 <code>phoneNumber</code> is declared in a document, you can refer to this variable from an iframe as <code>parent.phoneNumber</code>.</p> - -<h3 dir="rtl" id="Constants">Constants</h3> - -<p dir="rtl">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.</p> - -<pre class="brush: js" dir="rtl">const PI = 3.14; -</pre> - -<p dir="rtl">A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.</p> - -<p dir="rtl">The scope rules for constants are the same as those for <code>let</code> block scope variables. If the <code>const</code> keyword is omitted, the identifier is assumed to represent a variable.</p> - -<p dir="rtl">You cannot declare a constant with the same name as a function or variable in the same scope. For example:</p> - -<pre class="brush: js" dir="rtl">// THIS WILL CAUSE AN ERROR -function f() {}; -const f = 5; - -// THIS WILL CAUSE AN ERROR ALSO -function f() { - const g = 5; - var g; - - //statements -} -</pre> - -<p dir="rtl">However, the properties of objects assigned to constants are not protected, so the following statement is executed without problems.</p> - -<pre class="brush: js" dir="rtl">const MY_OBJECT = {"key": "value"}; -MY_OBJECT.key = "otherValue";</pre> - -<h2 dir="rtl" id="Data_structures_and_types">Data structures and types</h2> - -<h3 dir="rtl" id="Data_types">Data types</h3> - -<p dir="rtl">The latest ECMAScript standard defines seven data types:</p> - -<ul dir="rtl"> - <li>Six data types that are {{Glossary("Primitive", "primitives")}}: - <ul> - <li>{{Glossary("Boolean")}}. <code>true</code> and <code>false</code>.</li> - <li>{{Glossary("null")}}. A special keyword denoting a null value. Because JavaScript is case-sensitive, <code>null</code> is not the same as <code>Null</code>, <code>NULL</code>, or any other variant.</li> - <li>{{Glossary("undefined")}}. A top-level property whose value is undefined.</li> - <li>{{Glossary("Number")}}. <code>42</code> or <code>3.14159</code>.</li> - <li>{{Glossary("String")}}. "Howdy"</li> - <li>{{Glossary("Symbol")}} (new in ECMAScript 2015). A data type whose instances are unique and immutable.</li> - </ul> - </li> - <li>and {{Glossary("Object")}}</li> -</ul> - -<p dir="rtl">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.</p> - -<h3 dir="rtl" id="Data_type_conversion">Data type conversion</h3> - -<p dir="rtl">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:</p> - -<pre class="brush: js" dir="rtl">var answer = 42; -</pre> - -<p dir="rtl">And later, you could assign the same variable a string value, for example:</p> - -<pre class="brush: js" dir="rtl">answer = "Thanks for all the fish..."; -</pre> - -<p dir="rtl">Because JavaScript is dynamically typed, this assignment does not cause an error message.</p> - -<p dir="rtl">In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:</p> - -<pre class="brush: js" dir="rtl">x = "The answer is " + 42 // "The answer is 42" -y = 42 + " is the answer" // "42 is the answer" -</pre> - -<p dir="rtl">In statements involving other operators, JavaScript does not convert numeric values to strings. For example:</p> - -<pre class="brush: js" dir="rtl">"37" - 7 // 30 -"37" + 7 // "377" -</pre> - -<h3 dir="rtl" id="Converting_strings_to_numbers">Converting strings to numbers</h3> - -<p dir="rtl">In the case that a value representing a number is in memory as a string, there are methods for conversion.</p> - -<ul dir="rtl"> - <li id="parseInt()_and_parseFloat()">{{jsxref("parseInt", "parseInt()")}}</li> - <li>{{jsxref("parseFloat", "parseFloat()")}}</li> -</ul> - -<p dir="rtl"><code>parseInt</code> will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for <code>parseInt</code> is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.</p> - -<p dir="rtl">An alternative method of retrieving a number from a string is with the <code>+</code> (unary plus) operator:</p> - -<pre class="brush: js" dir="rtl">"1.1" + "1.1" = "1.11.1" -(+"1.1") + (+"1.1") = 2.2 -// Note: the parentheses are added for clarity, not required.</pre> - -<h2 dir="rtl" id="Literals">Literals</h2> - -<p dir="rtl">You use literals to represent values in JavaScript. These are fixed values, not variables, that you <em>literally</em> provide in your script. This section describes the following types of literals:</p> - -<ul dir="rtl"> - <li>{{anch("Array literals")}}</li> - <li>{{anch("Boolean literals")}}</li> - <li>{{anch("Floating-point literals")}}</li> - <li>{{anch("Integers")}}</li> - <li>{{anch("Object literals")}}</li> - <li>{{anch("RegExp literals")}}</li> - <li>{{anch("String literals")}}</li> -</ul> - -<h3 dir="rtl" id="Array_literals">Array literals</h3> - -<p dir="rtl">An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets (<code>[]</code>). 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.</p> - -<p dir="rtl">The following example creates the <code>coffees</code> array with three elements and a length of three:</p> - -<pre class="brush: js" dir="rtl">var coffees = ["French Roast", "Colombian", "Kona"]; -</pre> - -<div class="note" dir="rtl"> -<p><strong>Note :</strong> An array literal is a type of object initializer. See <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers">Using Object Initializers</a>.</p> -</div> - -<p dir="rtl">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.</p> - -<p dir="rtl">Array literals are also <code>Array</code> objects. See {{jsxref("Array")}} and <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> for details on <code>Array</code> objects.</p> - -<h4 dir="rtl" id="Extra_commas_in_array_literals">Extra commas in array literals</h4> - -<p dir="rtl">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 <code>undefined</code> for the unspecified elements. The following example creates the <code>fish</code> array:</p> - -<pre class="brush: js" dir="rtl">var fish = ["Lion", , "Angel"]; -</pre> - -<p dir="rtl">This array has two elements with values and one empty element (<code>fish[0]</code> is "Lion", <code>fish[1]</code> is <code>undefined</code>, and <code>fish[2]</code> is "Angel").</p> - -<p dir="rtl">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 <code>myList[3]</code>. All other commas in the list indicate a new element.</p> - -<div class="note" dir="rtl"> -<p><strong>Note :</strong> Trailing commas can create errors in older browser versions and it is a best practice to remove them.</p> -</div> - -<pre class="brush: js" dir="rtl">var myList = ['home', , 'school', ]; -</pre> - -<p dir="rtl">In the following example, the length of the array is four, and <code>myList[0]</code> and <code>myList[2]</code> are missing.</p> - -<pre class="brush: js" dir="rtl">var myList = [ , 'home', , 'school']; -</pre> - -<p dir="rtl">In the following example, the length of the array is four, and <code>myList[1]</code> and <code>myList[3]</code> are missing. Only the last comma is ignored.</p> - -<pre class="brush: js" dir="rtl">var myList = ['home', , 'school', , ]; -</pre> - -<p dir="rtl">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 <code>undefined</code> will increase your code's clarity and maintainability.</p> - -<h3 dir="rtl" id="Boolean_literals">Boolean literals</h3> - -<p dir="rtl">The Boolean type has two literal values: <code>true</code> and <code>false</code>.</p> - -<p dir="rtl">Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> 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.</p> - -<h3 dir="rtl" id="Integers">Integers</h3> - -<p dir="rtl">Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).</p> - -<ul dir="rtl"> - <li>Decimal integer literal consists of a sequence of digits without a leading 0 (zero).</li> - <li>Leading 0 (zero) on an integer literal, or leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.</li> - <li>Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.</li> - <li> - <p>Leading 0b (or 0B) indicates binary. Binary integers can include digits only 0 and 1.</p> - </li> -</ul> - -<p dir="rtl">Some examples of integer literals are:</p> - -<pre class="eval" dir="rtl">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) -</pre> - -<p dir="rtl">For more information, see <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">Numeric literals in the Lexical grammar reference</a>.</p> - -<h3 dir="rtl" id="Floating-point_literals">Floating-point literals</h3> - -<p dir="rtl">A floating-point literal can have the following parts:</p> - -<ul dir="rtl"> - <li>A decimal integer which can be signed (preceded by "+" or "-"),</li> - <li>A decimal point ("."),</li> - <li>A fraction (another decimal number),</li> - <li>An exponent.</li> -</ul> - -<p dir="rtl">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").</p> - -<p dir="rtl">More succinctly, the syntax is:</p> - -<pre class="eval" dir="rtl">[(+|-)][digits][.digits][(E|e)[(+|-)]digits] -</pre> - -<p dir="rtl">For example:</p> - -<pre class="eval" dir="rtl">3.1415926 --.123456789 --3.1E+12 -.1e-23 -</pre> - -<h3 dir="rtl" id="Object_literals">Object literals</h3> - -<p dir="rtl">An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (<code>{}</code>). 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.</p> - -<p dir="rtl">The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>, and assigns to it a new string, "<code>Saturn</code>"; the second element, the <code>getCar</code> property, is immediately assigned the result of invoking the function <code>(carTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>sales</code>).</p> - -<pre class="brush: js" dir="rtl">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 -</pre> - -<p dir="rtl">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.</p> - -<pre class="brush: js" dir="rtl">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; - -console.log(car.manyCars.b); // Jeep -console.log(car[7]); // Mazda -</pre> - -<p dir="rtl">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 (<code>.</code>) property, but can be accessed and set with the array-like notation("<code>[]</code>").</p> - -<pre class="brush: js" dir="rtl">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!</pre> - -<p dir="rtl">In ES2015, object literals are extended to support setting the prototype at construction, shorthand for <code>foo: foo</code> 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.</p> - -<pre class="brush: js" dir="rtl">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 -};</pre> - -<p dir="rtl">Please note:</p> - -<pre class="brush: js" dir="rtl">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 -</pre> - -<h3 dir="rtl" id="RegExp_literals">RegExp literals</h3> - -<p dir="rtl">A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.</p> - -<pre class="brush: js" dir="rtl">var re = /ab+c/;</pre> - -<h3 dir="rtl" id="String_literals">String literals</h3> - -<p dir="rtl">A string literal is zero or more characters enclosed in double (<code>"</code>) or single (<code>'</code>) 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:</p> - -<pre class="brush: js" dir="rtl">"foo" -'bar' -"1234" -"one line \n another line" -"John's cat" -</pre> - -<p dir="rtl">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 <code>String.length</code> property with a string literal:</p> - -<pre class="brush: js" dir="rtl">console.log("John's cat".length) -// Will print the number of symbols in the string including whitespace. -// In this case, 10. -</pre> - -<p dir="rtl">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.</p> - -<pre class="brush: js" dir="rtl">// 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);</pre> - -<p dir="rtl">You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on <code>String</code> objects.</p> - -<h4 dir="rtl" id="Using_special_characters_in_strings">Using special characters in strings</h4> - -<p dir="rtl">In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p> - -<pre class="brush: js" dir="rtl">"one line \n another line" -</pre> - -<p dir="rtl">The following table lists the special characters that you can use in JavaScript strings.</p> - -<table class="standard-table" dir="rtl"> - <caption> - <p>Table: JavaScript special characters</p> - </caption> - <thead> - <tr> - <th scope="col">Character</th> - <th scope="col">Meaning</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>\0</code></td> - <td>Null Byte</td> - </tr> - <tr> - <td><code>\b</code></td> - <td>Backspace</td> - </tr> - <tr> - <td><code>\f</code></td> - <td>Form feed</td> - </tr> - <tr> - <td><code>\n</code></td> - <td>New line</td> - </tr> - <tr> - <td><code>\r</code></td> - <td>Carriage return</td> - </tr> - <tr> - <td><code>\t</code></td> - <td>Tab</td> - </tr> - <tr> - <td><code>\v</code></td> - <td>Vertical tab</td> - </tr> - <tr> - <td><code>\'</code></td> - <td>Apostrophe or single quote</td> - </tr> - <tr> - <td><code>\"</code></td> - <td>Double quote</td> - </tr> - <tr> - <td><code>\\</code></td> - <td>Backslash character</td> - </tr> - <tr> - <td><code>\<em>XXX</em></code></td> - <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td> - </tr> - <tr> - </tr> - <tr> - <td><code>\x<em>XX</em></code></td> - <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td> - </tr> - <tr> - </tr> - <tr> - <td><code>\u<em>XXXX</em></code></td> - <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a>.</td> - </tr> - <tr> - <td><code>\u<em>{XXXXX}</em></code></td> - <td>Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.</td> - </tr> - </tbody> -</table> - -<h4 dir="rtl" id="Escaping_characters">Escaping characters</h4> - -<p dir="rtl">For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p> - -<p dir="rtl">You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p> - -<pre class="brush: js" dir="rtl">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; -console.log(quote); -</pre> - -<p dir="rtl">The result of this would be:</p> - -<pre class="eval" dir="rtl">He read "The Cremation of Sam McGee" by R.W. Service. -</pre> - -<p dir="rtl">To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p> - -<pre class="brush: js" dir="rtl">var home = "c:\\temp"; -</pre> - -<p dir="rtl">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.</p> - -<pre class="brush: js" dir="rtl">var str = "this string \ -is broken \ -across multiple\ -lines." -console.log(str); // this string is broken across multiplelines. -</pre> - -<p dir="rtl">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:</p> - -<pre class="brush: js" dir="rtl">var poem = -"Roses are red,\n\ -Violets are blue.\n\ -Sugar is sweet,\n\ -and so is foo." -</pre> - -<h2 dir="rtl" id="More_information">More information</h2> - -<p dir="rtl">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:</p> - -<ul dir="rtl"> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Control flow and error handling</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a></li> -</ul> - -<p dir="rtl">In the next chapter, we will have a look at control flow constructs and error handling.</p> - -<p dir="rtl">{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</p> 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/راهنما ---- -<p>{{jsSidebar("JavaScript Guide")}}</p> - -<div class="summary"> -<p style="direction: rtl;"><span class="seoSummary">راهنمای javascript یک مرور اجمالی بر روی این زبان داشته و به شما طریقه استفاده از<a href="/en-US/docs/Web/JavaScript"> جاوا اسکریپت</a> را نشان می دهد. اگر می خواهید به طور کلی برنامه نویسی یا جاوا اسکریپت را شروع کنید, از مقالات ما در <a href="/en-US/Learn">محیط آموزشی</a> کمک بگیرید. اگر به اطلاعات کامل درباره ویژگی های یک زبان نیاز دارید، نگاهی به<a href="/en-US/docs/Web/JavaScript/Reference"> مرجع جاوا اسکریپت</a> داشته باشید</span></p> -</div> - -<ul class="card-grid"> - <li><strong><a href="/en-US/docs/Web/JavaScript/Guide/Introduction">معرفی</a></strong> - - <p><a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Where_to_find_JavaScript_information">درباره این راهنما</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#What_is_JavaScript.3F">درباره جاوا اسکریپت</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_Java">جاوا اسکریپت و جاوا</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_the_ECMAScript_Specification">ECMAScript</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Getting_started_with_JavaScript">ابزارها</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Hello_world">مثال Hello World</a> </p> - </li> - <li><strong><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types">دستور زبان و نوع های داده ای</a></strong> - <p><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Basics">syntax اولیه و commentها</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations">تعاریف</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope">Variable scope</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting">Variable hoisting</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types">ساختار داده و نوع های داده ای</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Literals">Literals</a></p> - </li> - <li><strong><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">روند کنترل و مدیریت خطا</a></strong> - <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#if...else_statement">if...else</a></code><br> - <code><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#switch_statement">switch</a></code><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Exception_handling_statements"><code>try</code>/<code>catch</code>/<code>throw</code></a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Utilizing_Error_objects">Error objects</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Promises">Promises</a></p> - </li> - <li><strong><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">حلقه ها و تکرار</a></strong> - <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement">for</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#while_statement">while</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#do...while_statement">do...while</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#break_statement">break</a>/<a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#continue_statement">continue</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement">for..in</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for..of</a></code></p> - </li> -</ul> - -<ul class="card-grid"> - <li><strong><a href="/en-US/docs/Web/JavaScript/Guide/Functions">توابع</a></strong> - - <p><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Defining_functions">تعریف توابع</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions">فراخوانی توابع</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope">Function scope</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Closures">Closures</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Using_the_arguments_object">Arguments</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_parameters">parameters</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Arrow_functions">Arrow functions</a></p> - </li> - <li><strong><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">عبارات و عملگرها</a></strong> - <p><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment_operators">مقدار دهی</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison_operators">مقایسه</a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators">عملگرهای ریاضی</a><br> - <span style="background-color: rgba(234, 239, 242, 0.498039);">عملگرهای </span><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">بیتی</a> و <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators">منطقی </a><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Conditional_(ternary)_operator">عملگرهای شرطی (سه تایی)</a></p> - </li> - <li><strong><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates">اعداد و تاریخ</a></strong><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers"> </a> - <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers">Number literals</a></code><br> - <code><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Number_object">Number object</a></code><br> - <a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Math_object"><code>Math</code> object</a><br> - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Date_object"><code>Date</code> object</a></p> - </li> - <li><strong><a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting">قالب بندی متن</a></strong> - <p>رشته ها<br> - Template strings<br> - Regular Expressions<br> - Internationalization<br> - </p> - </li> - <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">مجموعه های اندیس دار</a></span> - <p>آرایه ها<br> - آریه های نوع دار</p> - </li> - <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections_and_structured_data">مجموعه های کلید دار و داده های ساخت یافته</a></span> - <p>Maps, WeakMaps<br> - Sets, WeakSets<br> - JSON</p> - </li> - <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects">کار با اشیا</a></span> - <p>ایجاد اشیا<br> - Object initializer<br> - وراثت<br> - Getter and setter</p> - </li> - <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">جزئیات مدل شی</a></span> - <p>Prototype-based OOP<br> - Properties and methods<br> - وراثت</p> - </li> - <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterators and generators</a></span> - <p>Iterable protocol<br> - Iterator protocol<br> - Generators</p> - </li> - <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming">Meta programming</a></span> - <p>Proxy<br> - Reflect</p> - </li> -</ul> - -<p>{{Next("Web/JavaScript/Guide/Introduction")}}</p> 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/راهنما/مقدمه ---- -<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</div> - -<p class="summary" dir="rtl">در این فصل به مباحث مقدماتی جاوا اسکریپت پرداخته و برخی از مفاهیم اساسی آن را بیان می کنیم . </p> - -<h2 dir="rtl" id="آنچه_که_شما_باید_از_قبل_بدانید">آنچه که شما باید از قبل بدانید</h2> - -<p dir="rtl">این آموزش فرض را بر این گرفته که شما پیش زمینه های زیر را دارا هستید:</p> - -<ul dir="rtl"> - <li>یک درک عمومی از اینترنت و شبکه ی جهانی وب ({{Glossary("WWW")}}).</li> - <li>اطلاعاتی خوب و کارآمد در زمینه ی زبان نشانه گذاری فرا متن ({{Glossary("HTML")}}).</li> -</ul> - -<p dir="rtl">مقداری تجربه ی برنامه نویسی . اگر شما به تازگی وارد برنامه نویسی شده اید ، سعی کنید ابتدا از لینک های آموزشی که در صفحه ی اصلی هست به لینک درباره ی جاوا اسکریپت بروید.</p> - -<h2 dir="rtl" id="کجا_اطلاعات_جاوا_اسکریپت_را_پیدا_کنید">کجا اطلاعات جاوا اسکریپت را پیدا کنید</h2> - -<p dir="rtl">مستندات جاوا اسکریپت در MDN شامل موارد زیر است:</p> - -<ol dir="rtl"> - <li><a href="/en-US/Learn">یادگیری وب:</a> اطلاعاتی را برای افراد تازه کار فراهم می کند و همچنین مفاهیم پایه برنامه نویسی و اینترنت را معرفی می کند</li> - <li><a href="/en-US/docs/Web/JavaScript/Guide">راهنمای جاوا اسکریپت:</a> (این راهنمایی) یک دیدکلی را از زبان جاوا اسکریپت و اشیای آن ارائه می کند</li> - <li><a href="/en-US/docs/Web/JavaScript/Reference">مرجع جاوا اسکریپت:</a> یک مرجع همراه با جزئیات برای زبان جاوا اسکریپت فراهم می کند</li> -</ol> - -<h2 dir="rtl" id="جاوا_اسکریپت_چیست؟">جاوا اسکریپت چیست؟</h2> - -<p dir="rtl">جاوا اسکریپت یک زبان با بسترمتقاطع(چند پلتفرمی) و شی گرای اسکریپتی است. این زبان کوچک و سبک است. در محیط میزبان (برای مثال یک مرورگر) جاوا اسکریپت می تواند به اشیای محیط متصل شده و کنترل به وسیله برنامه نویسی را برای آن محیط فراهم می کند.</p> - -<p dir="rtl">جاوا اسکریپت شامل یک کتابخانه استاندارد اشیا است مانند Array، Date و Math، مجموعه پایه ای از عناصر زبان مثل عملگرها، ساختارهای کنترلی و عبارات. هسته ی زبان جاوا اسکریپت می تواند برای اهداف مختلفی توسعه داده شود. برای این منظور از جاوا اسکریپت به همراه اشیایی اضافی استفاده می شود برای مثال:</p> - -<ul> - <li dir="rtl">جاوا اسکریپت سمت مشتری(کلاینت): هسته زبان را با استفاده از اشیایی توسعه می دهد که مرورگر و ساختار DOM آن را کنترل می کند. برای مثال افزونه های سمت مشتری به برنامه اجازه می دهند تا عناصری را در یک فرم HTML قرار دهد و به رویدادهای کاربر مانند کلیک های موس، ورودی های فرم،... پاسخ دهد.</li> - <li dir="rtl">جاوا اسکریپت سمت خادم(سرور): هسته جاوا اسکریپت را با استفاده از اشیایی که به اجرا شدن جاوا اسکریپت بر روی سرور مربوط می شود توسعه می دهد. برای مثال افزونه های سمت سرور به برنامه اجازه می دهند تا با پایگاه داده ارتباط برقرار کند،</li> -</ul> - -<h2 dir="rtl" id="JavaScript_and_Java" name="JavaScript_and_Java">جاوا اسکریپت و جاوا</h2> - -<p dir="rtl">جاوااسکریپت و جاوا از بعضی جهات با هم مشابه</p> - -<p>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.</p> - -<p>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.</p> - -<p>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.</p> - -<p>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.</p> - -<table class="standard-table"> - <caption>JavaScript compared to Java</caption> - <thead> - <tr> - <th scope="col">JavaScript</th> - <th scope="col">Java</th> - </tr> - </thead> - <tbody> - <tr> - <td>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.</td> - <td>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.</td> - </tr> - <tr> - <td>Variable data types are not declared (dynamic typing).</td> - <td>Variable data types must be declared (static typing).</td> - </tr> - <tr> - <td>Cannot automatically write to hard disk.</td> - <td>Can automatically write to hard disk.</td> - </tr> - </tbody> -</table> - -<p>For more information on the differences between JavaScript and Java, see the chapter <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">Details of the object model</a>.</p> - -<h2 dir="rtl" id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">مشخصات جاوا اسکریپت و اکما اسکریپت</h2> - -<p dir="rtl">جاوا اسکریپت در <a href="http://www.ecma-international.org/">Ecma International</a> استاندارد شده است —اتحادیه اروپا برای استاندارد سازی سیستم های اطلاعاتی و ارتباطی (ECMA مخفف انجمن سازندگان کامپیوتری اروپا) بود تا یک زبان برنامه نویسی استاندارد مبتنی بر جاوا اسکریپت را ارائه کند.</p> - -<p dir="rtl">این نسخه استاندارد از جاوا اسکریپت، به نام اکما اسکریپت ، در تمامی برنامه هایی که از استاندارد پشتیبانی می کنند، یکسان عمل می کند. شرکت ها می توانند از استاندارد زبان باز برای توسعه جاوا اسکریپت خود استفاده کنند. استاندارد اکما اسکریپت در مشخصات ECMA-262 مستند شده است. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript">تازه ها</a> در جاوا اسکریپت را برای کسب اطلاعات بیشتر در مورد نسخه های مختلف نسخه های خاص جاوا اسکریپت و اکما اسکریپت مشاهده کنید.</p> - -<p dir="rtl">The ECMA-262 standard is also approved by the <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization) as ISO-16262. You can also find the specification on <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a>. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a> and/or <a href="https://whatwg.org">WHATWG (Web Hypertext Application Technology Working Group)</a>. 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 <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> - -<h3 dir="rtl" id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">مستندات جاوا اسکریپت در مقایسه با مشخصات اکما اسکریپت</h3> - -<p dir="rtl">مشخصات اکما اسکریپت مجموعه ای از الزامات برای پیاده سازی اکما اسکریپت است؛ اگر شما می خواهید ویژگی های زبان سازگار با استاندارد را در پیاده سازی اکما اسکریپت یا موتور خود (مانند SpiderMonkey در فایرفاکس یا v8 در Chrome) پیاده سازی کنید، مفید است.</p> - -<p>The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.</p> - -<p>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.</p> - -<p>The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.</p> - -<h2 dir="rtl" id="شروع_با_جاوا_اسکریپت">شروع با جاوا اسکریپت</h2> - -<p>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.</p> - -<p>There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.</p> - -<h3 dir="rtl" id="کنسول_وب">کنسول وب</h3> - -<p>The <a href="/en-US/docs/Tools/Web_Console">Web Console</a> shows you information about the currently loaded Web page, and also includes a <a href="/en-US/docs/Tools/Web_Console#The_command_line_interpreter">command line</a> that you can use to execute JavaScript expressions in the current page.</p> - -<p>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:</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/7363/web-console-commandline.png" style="display: block; margin-left: auto; margin-right: auto;"></p> - -<h3 id="Scratchpad">Scratchpad</h3> - -<p>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 <a href="/en-US/docs/Tools/Scratchpad">Scratchpad</a> is a better tool.</p> - -<p>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.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/7365/scratchpad.png" style="display: block; margin-left: auto; margin-right: auto;"></p> - -<h3 id="Hello_world">Hello world</h3> - -<p>To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:</p> - -<pre class="brush: js">function greetMe(yourName) { - alert("Hello " + yourName); -} - -greetMe("World"); -</pre> - -<p>Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!</p> - -<p>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.</p> - -<p>{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</p> 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 ---- -<div class="callout-box"><strong><a href="/fa/docs/Web/JavaScript/A_re-introduction_to_JavaScript">یک معرفی مجدد برای جاوااسکریپت</a></strong><br> -یک بررسی کلی برا آنهایی که <em>فکر میکنند</em> در مورد جاوااسکریپت میدانند</div> - -<p dir="rtl">{{JsSidebar}}</p> - -<p dir="rtl"><strong>JavaScript</strong><sup>®</sup> (اغلب به <strong>JS</strong> مخفف میشود) سبک، مفسر، زبان شیگرا شده با <a href="https://en.wikipedia.org/wiki/First-class_functions" title="https://en.wikipedia.org/wiki/First-class_functions">first-class functions</a>، به عنوان زبان اسکریپت نویسی برای صفحات وب شناخته شده است، اما <a class="external" href="http://en.wikipedia.org/wiki/JavaScript#Uses_outside_web_pages">در خیلی از محیطهای غیر مرورگری</a> مانند <a class="external" href="http://nodejs.org/">node.js</a> یا <a href="http://couchdb.apache.org">Apache CouchDB</a> نیز استفاده شده است. زبان اسکریت نویسی آن <a class="mw-redirect" href="https://en.wikipedia.org/wiki/Prototype-based" title="Prototype-based">مبتنی بر نمونه</a> است، <a href="/en-US/docs/multiparadigmlanguage.html" title="/en-US/docs/multiparadigmlanguage.html">چند نمونه</a> که پویا است،<span style="color: #666666; line-height: 21px;"> </span><a href="https://en.wikipedia.org/wiki/Type_safety" style="line-height: 21px;" title="Type safety">نوع امن</a><span style="line-height: 1.572;"> و از شی گرایی پشتیبانی میکند، سبک های برنامه نویسی تابعی را دارد. اطلاعات بیشتر را میتوانید از صفحه <a href="/fa/docs/docs/Web/JavaScript/About_JavaScript">درباره جاوااسکریپت</a></span><span style="line-height: 1.572;"> مشاهده نمایید.</span></p> - -<p dir="rtl">استاندارد جاوااسکریپت <a href="/fa/docs/JavaScript/Language_Resources">اکمااسکریپت</a> (<a href="/fa/docs/JavaScript/Language_Resources">ECMAScript</a>) است که از سال ۲۰۱۲ تمامی مرورگرهای مدرن استاندارد اکمااسکریپت نسخه ۵.۱ را به صورت کامل پشتیبانی میکنند، همچنین مرورگرهای قدیمیتر نسخه ۳ از اکمااسکریپت را پشتیبانی میکنند. از ماه June سال ۲۰۱۵ اکمااسکریپت ۶ (ES6) یا همان اکمااسکریپت ۲۰۱۵ (ES2015) مورد قبول واقع شده است. توضیحات تکمیلی در مورد اکمااسکریپت ۶ را می توانید در <a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proposals">dedicated wiki</a> مشاهده نمایید.</p> - -<p dir="rtl">این بخش از سایت به زبان جاوااسکریپت اختصاص داده شده است، قسمتهایی که مختص به صفحات وب، یا دیگر محیطهای میزبانی نیست. برای اطلاعات در مورد APIهای خاص برای صفحات وب، لطفا <a href="/fa/docs/DOM">DOM</a> را ببینید. در مورد اینکه چگونه DOM وJavaScript با همدیگر مناسب هستند در <a href="/fa/docs/Gecko_DOM_Reference/Introduction#DOM_and_JavaScript">مرجع DOM</a> اطلاعات بیشتری را بخوانید.</p> - -<p dir="rtl">JavaScript به صورت <strong>«جاواسکریپت»</strong> خوانده میشود، ولی در فارسی به صورت <strong>«جاوااسکریپت»</strong> ترجمه میشود و اگر به صورت «جاوا اسکریپت» ترجمه شود اشتباه است چون دو کلمه جدا از هم نیست و اگر به صورت دو کلمه جدا نوشته شود خطلاهای نگارشی ایجاد میشود، به طور مثال ممکن است کلمه جاوا در انتهای خط و کلمه اسکریپت در ابتدای خط بعدی نوشته شود.</p> - -<div class="row topicpage-table" dir="rtl"> -<div class="section"> -<h2 class="Documentation" id="مستندات">مستندات</h2> - -<dl> - <dt><a href="/fa/docs/Web/JavaScript/Guide">راهنمای جاوااسکریپت</a></dt> - <dd>اگر شما در جاوااسکریپت تازهکار هستید، باید این راهنما را بخوانید.</dd> - <dt><a href="/fa/docs/Web/JavaScript/Reference">مرجع جاوااسکریپت</a></dt> - <dd>این مرجع جاوااسکریپت شامل مستندات کاملی برای جاوااسکریپت نسخه ۱.۵ و بهروزرسانیهای آن است.</dd> -</dl> - -<h3 id="مقالات_معرفی">مقالات معرفی</h3> - -<dl> - <dt><a href="/fa/docs/Web/JavaScript/JavaScript_technologies_overview">نمای کلی تکنولوژیهای جاوااسکریپت</a></dt> - <dd>آشنایی با چشم انداز جاوااسکریپت برای مرورگر</dd> -</dl> - -<h3 id="مقالات_پیشرفته">مقالات پیشرفته</h3> - -<dl> - <dt><a href="/fa/docs/Web/JavaScript/Data_structures">ساختارهای دادهای جاوااسکریپت</a></dt> - <dd>نمای کلی ساختارهای دادهای قابل دسترس در جاپااسکریپت</dd> - <dt><a href="/fa/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">وراثت و زنجیره نمونه</a></dt> - <dd>توضیح ارثبری مبتنی بر نمونه که بهصورت گستردهای اشتباده و ناچیز شمرده شده است</dd> -</dl> - -<h3 id="مقالات_دیگر">مقالات دیگر</h3> - -<dl> - <dt><a href="/fa/docs/Web/Guide/HTML/Canvas_tutorial">آموزش بوم نقاشی</a></dt> - <dd><canvas> یک المان HTML5 است که برای رسم گرافیکها با استفاده از اسکریپت نویسی استفاده میشود. آن میتواند، برای مثال برای رسم گرافیکها، ترکیب عکس و یا انجام ساده (و نه خیلی ساده) انیمیشنها استفاده شود.</dd> - <dt><a href="/fa/docs/Web/JavaScript/Language_Resources">مراجع زبان جاوااسکریپت</a></dt> - <dd>شرح زبان جاوااسکریپت استاندارد.</dd> - <dt><a class="external" href="http://msdn.microsoft.com/en-us/library/ff405926.aspx">مستندات پشتیبانی استانداردهای اینترنت اکسپلورر</a></dt> - <dd>مایکروسافت مستنداتی منتشر کرده است که "تغییرات، توضیحات، و الحاقیات برخی استانداردهای مورد تایید پشتیبانی شده توسط اینترنت اکسپلورر." را شرح میدهد، بعضی از آنها مربوط به جاوااسکریپت هستند:</dd> - <dd> - <ul> - <li><a class="external" href="http://msdn.microsoft.com/en-us/library/ff520996.aspx">[MS-ES3]: Internet Explorer ECMA-262 ECMAScript Language Specification Standards Support Document </a></li> - <li><a class="external" href="http://msdn.microsoft.com/en-us/library/ff521046.aspx">[MS-ES3EX]: Microsoft JScript Extensions to the ECMAScript Language Specification Third Edition </a></li> - <li><a class="external" href="http://msdn.microsoft.com/en-us/library/ff960769.aspx">[MS-ES5]: Internet Explorer ECMA-262 ECMAScript Language Specification (Fifth Edition) Standards Support Document </a></li> - <li><a class="external" href="http://msdn.microsoft.com/en-us/library/ff955363.aspx">[MS-ES5EX]: Internet Explorer Extensions to the ECMA-262 ECMAScript Language Specification (Fifth Edition)</a></li> - </ul> - </dd> -</dl> - -<p><span class="alllinks"><a href="/en-US/docs/tag/JavaScript">View All...</a></span></p> -</div> - -<div class="section"> -<h2 class="Tools" id="ابزارها_منابع_پیشرفته">ابزارها & منابع پیشرفته</h2> - -<ul> - <li><a href="/fa/docs/Tools">ابزارهای توسعه فایرفاکس</a> - ابزارهای عالی تعبیه شده در فایرفاکس.</li> - <li><a href="http://koding.com">Koding</a> پلت فرم توسعه آنلاین با پشتیبانی جاوااسکریپت</li> - <li><a href="http://www.learnstreet.com/">LearnStreet</a> - آموزشها و تمرینهای عملی رایگان آنلاین.</li> - <li><a href="http://www.codecademy.com/">Codecademy</a> - دوره جاوااسکریپت رایگان با مشکلات تعاملی</li> - <li><a href="http://codeschool.com">Code School </a>- یادگیری بوسیله انجام دادن، چندین دوره جاو.ا اسکریپت</li> - <li><a href="http://frontendmasters.com/" title="http://frontendmasters.com/">Frontend Masters</a> - فیلمهای کارگاه آموزشی جاوااسکریپت و توسعه وب نهایی</li> - <li><a href="http://www.letscodejavascript.com/" title="http://www.letscodejavascript.com/">Let’s Code: Test-Driven JavaScript</a> - سریهای ضبط خیلی دقیق صفحه، توسعه حرفهای جاوااسکریپت</li> - <li><a class="link-https" href="https://github.com/rwldrn/idiomatic.js">Idiomatic.js</a> - اصول نوشتن جاوااسکریپت استوار، اصطلاحی</li> - <li><a href="/en-US/docs/JavaScript/Memory_Management">Memory Management in JavaScript</a> . نمای کلی از چگونگی عملکرد حافظه در جاوااسکریپت</li> - <li><a class="external" href="http://www.getfirebug.com/">Firebug</a> - اشکالزدایی و پروفایلینگ جاوااسکریپت</li> - <li><a href="/en-US/docs/Venkman">Venkman</a> - دیباگر جاوااسکریپت</li> - <li><a href="/en-US/docs/JavaScript/Shells">JavaScript Shells</a> - تست قطعه کدهای کوچک</li> - <li><a class="external" href="http://jshint.com">JSHint</a> - ابزاری که در تشخیص خطا و مشکلات بالقوه در کد جاوااسکریپت شما کمک میکند</li> - <li><a class="external" href="http://www.jslint.com/lint.html">JSLint</a> - چک کننده نحو، در برابر اعمال بد هشدار میدهد</li> - <li><a class="external" href="http://usejsdoc.org/">JSDoc</a> - تولید مستندات از کد</li> - <li><a class="external" href="http://online-marketing-technologies.com/tools/javascript-redirection-generator.html" title="JavaScript Redirect">JavaScript Redirect</a> - ابزار تغییر مسیر پیشرفته جاوااسکریپت</li> - <li><a class="external" href="http://www.aptana.com">Aptana Studio</a> - <span id="result_box" lang="fa"><span class="hps">IDE</span> <span class="hps">متن باز</span> <span class="hps">با</span> پشتیبانی <span class="hps">آژاکس</span> <span class="hps">و</span> <span class="hps">جاوااسکریپت</span> <span class="atn hps">(</span><span>بر اساس</span> eclipse<span>)</span></span></li> - <li><a class="external" href="http://netbeans.org/features/javascript/">Netbeans</a> - IDE متن باز شامل پشتیبانی پیچیده از جاوااسکریپت</li> - <li><a class="external" href="http://www.eclipse.org/downloads/packages/eclipse-ide-javascript-web-developers/heliossr1">Eclipse</a> - IDE متن باز شامل جعبه ابزار توسعه جاوااسکریپت</li> - <li><a class="external" href="http://www.c9.io">Cloud9 IDE</a> - IDE متن باز که در مرورگر اجرا شده با قابلیت پشتیبانی از جاوااسکریپت و Node.js</li> - <li><a class="external" href="http://prettydiff.com/">Pretty Diff </a>- یک ابزار متفاوت برای مقایسه کد خرد شده با کد معمولی</li> - <li><a href="http://www.objectplayground.com/" title="http://www.objectplayground.com/">Object Playground</a> - ابزاری برای درک شیگرایی جاوااسکریپت</li> - <li><a class="link-https" href="https://addons.mozilla.org/en-US/firefox/addon/7434">Extension Developer's Extension</a> - محیط و شل JS را ارایه میدهد</li> - <li><a href="http://boilerplatejs.org/">BoilerplateJS</a> - مرجع معماری برای پروژههای جاوااسکریپت در مقیاس بزرگ</li> - <li><a href="http://www.jsfiddle.net/">JSFiddle</a> - مورد استفاده برای آزمایش و اصلاح وب سایت با جاوااسکریپت آنلاین. </li> - <li><a href="/fa/docs/JavaScript/Other_JavaScript_tools">دیگر ابزارهای جاوااسکریپت</a></li> -</ul> - -<p><span class="alllinks"><a href="/en-US/docs/tag/JavaScript:Tools">نمایش همه...</a></span></p> - -<h2 class="Community" id="Other_resources" name="Other resources">دیگر منابع</h2> - -<dl> - <dt><a class="external" href="http://bonsaiden.github.com/JavaScript-Garden">JavaScript Garden</a></dt> - <dd>سایتی با اطلاعات مفید در مورد قطعات داخلیتر جاوااسکریپت.</dd> - <dt><a class="link-https" href="https://github.com/bebraw/jswiki/wiki">JSWiki</a></dt> - <dd>یک ویکی مبتنی بر Githubکه منابع و کتابخانهها را ایندکس گذاری کرده است.</dd> - <dt><a href="http://stackoverflow.com/questions/tagged/javascript">Stack Overflow</a></dt> - <dd>یک سایت همکاری ساخته و نگهداری شده Q&A و میتوانید برای جواب سوال خودرا در آن جستجو کنید. اگر جواب سوال خودرا پیدا نکردید میتوانید سوال خودرا در آنجا مطرح کنید.</dd> - <dt><a href="http://pineapple.io/resources/tagged/javascript?type=tutorials&sort=all_time">Pineapple · JavaScript</a></dt> - <dd>یک پایگاه داده بزرگ از آموزش و منابع حال حاضر جاوااسکریپت.</dd> - <dt><a href="http://lifeofjs.com">Life of JavaScript</a></dt> - <dd>منابع عالی در مورد جاوااسکریپت شامل کتاب، ارایهها، فیلمها، فیدها، سایتها، کتابخانهها، محیطهای کاری، ابزارها که در یکجا جمع آموری شده است.</dd> -</dl> - -<h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">موضوعات مرتبط</h2> - -<ul> - <li><a href="/fa/docs/AJAX">AJAX</a>, <a href="/fa/docs/DOM">DOM</a>, <a class="internal" href="/fa/docs/JavaScript/Server-Side_JavaScript">Server-Side JavaScript</a>, <a href="/fa/docs/DHTML">DHTML</a>, <a href="/fa/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a>, <a href="/fa/docs/HTML/Canvas">Canvas</a>, <a href="/fa/docs/JavaScript/JQuery">JQuery</a></li> -</ul> -</div> -</div> 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 ---- -<div>{{jsSidebar("Advanced")}}</div> - -<p>جاوا اسکریپت ممکن است برای کسانی که با زبانهای شی گرا آشنایی دارند کمی گیج کننده باشد (زبانهایی مثل Java یاC++), بدلیل اینکه این زبان پویاست و کمپایل نمیشود و همچنین مفهومی به نام <code>class</code> را ندارد (البته واژه<code>class</code> در نسخه ES2015 معرفی شد, ولی در واقع فقط ظاهر قضیه عوض شده و در باطن کماکان ارث بری در جاوااسکریپت همان سیستم پروتوتایپ است).</p> - -<p>وقتی صحبت از وراثت باشد جاوا اسکریپت فقط یک شی دارد : objects.</p> - -<p>هر آبجکت در جاوااسکریپت یک مشخصه (<strong>property </strong>) مخفی دارد که به یک شی دیگر در رم اشاره میکند که این شی دوم همان <strong>پروتوتایپِ </strong>شی اول است. </p> - -<p> ، این پروتوتایپ هم برای خودش یک پروتوتایپ دارد و ... الی آخر . تا جایی که بالاترین شی در زنجیره پروتوتایپش <code>null</code> است . از آنجایی که <code>null</code> پروتوتایپ ندارد لذا این شی آخر حلقه در این زنجیره است . به این زنجیره ، <strong>زنجیره پروتوتایپ</strong> میگویند</p> - -<p>تقریبا همه اشیا در جاوا اسکریپت فرزند {{jsxref("Object")}} هستند که این شیء ، بالاترین شی در زنجیره پروتوتایپ است</p> - -<p>در حالیکه ممکن است این به عنوان یکی از ضعف های جاوااسکریپت به نظر بیاد ولی در واقع مدل ارث بری پروتوتایپی از مدل سنتی قدرتمند تر است . به طور مثال ساختن مدل سنتی ارث بری با استفاده از مدل پروتوتایپی کار بسیار ساده ای است.</p> - -<h2 id="ارث_بری_با_زنجیره_پروتوتایپ">ارث بری با زنجیره پروتوتایپ</h2> - -<h3 id="ارث_بری_خصوصیات_(properties)">ارث بری خصوصیات (properties)</h3> - -<p>اشیا در جاوا اسکریپت مثل کیف هایی پر از خصوصیات(properties) هستند . اشیا در این زبان همونطور که گفته شد یک لینک به پروتوتایپ خودشون هم دران . وقتی میخواهیم به یک خصوصیت از یک شی دسترسی پیدا کنیم اگر آن خصوصیت در خود شی پیدا نشد جاوا اسکریپت در پروتوتایپ دنبال آن خصوصیت میگردد ، اگر در آنجاهم نشد در پروتوتایپِ مربوط به آن پروتوتایپ و به همین ترتیب تا آخر زنجیره پروتوتایپ پیش میرود که یا property فراخوانی شده پیدا شود یا به انتهای زنجیره برسیم و جستجو تمام شود.</p> - -<div class="note"> -<p> در کدهای اکمااسکریپت زیر منظور از <code>someObject.[[Prototype]]</code> پروتوتایپِ <code>someObject</code> است . از ECMAScript 2015 پروتوتایپ )<code>[[Prototype]](</code> از طریق {{jsxref("Object.getPrototypeOf()")}} و یا {{jsxref("Object.setPrototypeOf()")}} قابل دسترسی است . این روش معادل است با استفاده از <code>__proto__</code> که روشی استاندارد نیست ولی در اکثر مرورگرها پیاده سازی شده و قابل استفاده است.</p> - -<p>این رو نباید با <code><em>func</em>.prototype</code> که در حقیقت یک property از توابع هست اشتباه کنیم ، که کاربردش هم جایی هست که بخواهیم همه اشیایی که توسط function مورد نظر ساخته شدن ، همه دارای پروتایپ دلخواه ما باشن</p> - -<p><code><strong>Object.prototype</strong></code> در واقع {{jsxref("Object")}} در زنجیره پروتوتایپ است</p> -</div> - -<p>وقتی ما یک propertyاز یک شی رو فراخونی میکنیم اتفاقی که میافته به این صورته :</p> - -<pre class="brush: js">// 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. -</pre> - -<p><a href="https://repl.it/@khaled_hossain_code/prototype">Code Link</a></p> - -<p>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 <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">getter or a setter</a>.</p> - -<h3 id="Inheriting_methods">Inheriting "methods"</h3> - -<p>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 <em>method overriding</em>).</p> - -<p>When an inherited function is executed, the value of <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> points to the inheriting object, not to the prototype object where the function is an own property.</p> - -<pre class="brush: js">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 - - -</pre> - -<h2 id="Using_prototypes_in_JavaScript">Using prototypes in JavaScript</h2> - -<p>Let's look at what happens behind the scenes in a bit more detail.</p> - -<p>In JavaScript, as mentioned above, functions are able to have properties. All functions have a special property named <code>prototype</code>. 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.</p> - -<pre class="brush: js">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 ); -</pre> - -<p>As seen above, <code>doSomething()</code> has a default <code>prototype</code> property, as demonstrated by the console. After running this code, the console should have displayed an object that looks similar to this.</p> - -<pre class="brush: js">{ - constructor: ƒ doSomething(), - __proto__: { - constructor: ƒ Object(), - hasOwnProperty: ƒ hasOwnProperty(), - isPrototypeOf: ƒ isPrototypeOf(), - propertyIsEnumerable: ƒ propertyIsEnumerable(), - toLocaleString: ƒ toLocaleString(), - toString: ƒ toString(), - valueOf: ƒ valueOf() - } -}</pre> - -<p>We can add properties to the prototype of <code>doSomething()</code>, as shown below.</p> - -<pre class="brush: js">function doSomething(){} -doSomething.prototype.foo = "bar"; -console.log( doSomething.prototype );</pre> - -<p>This results in:</p> - -<pre class="brush: js">{ - foo: "bar", - constructor: ƒ doSomething(), - __proto__: { - constructor: ƒ Object(), - hasOwnProperty: ƒ hasOwnProperty(), - isPrototypeOf: ƒ isPrototypeOf(), - propertyIsEnumerable: ƒ propertyIsEnumerable(), - toLocaleString: ƒ toLocaleString(), - toString: ƒ toString(), - valueOf: ƒ valueOf() - } -} -</pre> - -<p>We can now use the <code>new</code> operator to create an instance of <code>doSomething()</code> based on this prototype. To use the new operator, simply call the function normally except prefix it with <code>new</code>. Calling a function with the <code>new</code> operator returns an object that is an instance of the function. Properties can then be added onto this object.</p> - -<p>Try the following code:</p> - -<pre class="brush: js">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 );</pre> - -<p>This results in an output similar to the following:</p> - -<pre class="brush: js">{ - prop: "some value", - __proto__: { - foo: "bar", - constructor: ƒ doSomething(), - __proto__: { - constructor: ƒ Object(), - hasOwnProperty: ƒ hasOwnProperty(), - isPrototypeOf: ƒ isPrototypeOf(), - propertyIsEnumerable: ƒ propertyIsEnumerable(), - toLocaleString: ƒ toLocaleString(), - toString: ƒ toString(), - valueOf: ƒ valueOf() - } - } -}</pre> - -<p>As seen above, the <code>__proto__</code> of <code>doSomeInstancing</code> is <code>doSomething.prototype</code>. But, what does this do? When you access a property of <code>doSomeInstancing</code>, the browser first looks to see if <code>doSomeInstancing</code> has that property.</p> - -<p>If <code>doSomeInstancing</code> does not have the property, then the browser looks for the property in the <code>__proto__</code> of <code>doSomeInstancing</code> (a.k.a. doSomething.prototype). If the <code>__proto__</code> of doSomeInstancing has the property being looked for, then that property on the <code>__proto__</code> of doSomeInstancing is used.</p> - -<p>Otherwise, if the <code>__proto__</code> of doSomeInstancing does not have the property, then the <code>__proto__</code> of the <code>__proto__</code> of doSomeInstancing is checked for the property. By default, the <code>__proto__</code> of any function's prototype property is <code>window.Object.prototype</code>. So, the <code>__proto__</code> of the <code>__proto__</code> of doSomeInstancing (a.k.a. the <code>__proto__</code> of doSomething.prototype (a.k.a. <code>Object.prototype</code>)) is then looked through for the property being searched for.</p> - -<p>If the property is not found in the <code>__proto__</code> of the <code>__proto__</code> of doSomeInstancing, then the <code>__proto__</code> of the <code>__proto__</code> of the <code>__proto__</code> of doSomeInstancing is looked through. However, there is a problem: the <code>__proto__</code> of the <code>__proto__</code> of the <code>__proto__</code> of doSomeInstancing does not exist. Then, and only then, after the entire prototype chain of <code>__proto__</code>'s is looked through, and there are no more <code>__proto__</code>s does the browser assert that the property does not exist and conclude that the value at the property is <code>undefined</code>.</p> - -<p>Let's try entering some more code into the console:</p> - -<pre class="brush: js">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);</pre> - -<p>This results in the following:</p> - -<pre class="brush: js">doSomeInstancing.prop: some value -doSomeInstancing.foo: bar -doSomething.prop: undefined -doSomething.foo: undefined -doSomething.prototype.prop: undefined -doSomething.prototype.foo: bar</pre> - -<h2 id="Different_ways_to_create_objects_and_the_resulting_prototype_chain">Different ways to create objects and the resulting prototype chain</h2> - -<h3 id="Objects_created_with_syntax_constructs">Objects created with syntax constructs</h3> - -<pre class="brush: js">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 -</pre> - -<h3 id="With_a_constructor">With a constructor</h3> - -<p>A "constructor" in JavaScript is "just" a function that happens to be called with the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new operator</a>.</p> - -<pre class="brush: js">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. -</pre> - -<h3 id="With_Object.create">With <code>Object.create</code></h3> - -<p>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:</p> - -<pre class="brush: js">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 -</pre> - -<div> -<h3 id="With_the_class_keyword">With the <code>class</code> keyword</h3> - -<p>ECMAScript 2015 introduced a new set of keywords implementing <a href="/en-US/docs/Web/JavaScript/Reference/Classes">classes</a>. 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")}}.</p> - -<pre class="brush: js">'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); -</pre> - -<h3 id="Performance">Performance</h3> - -<p>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.</p> - -<p>Also, when iterating over the properties of an object, <strong>every</strong> enumerable property that is on the prototype chain will be enumerated. To check whether an object has a property defined on <em>itself</em> and not somewhere on its prototype chain, it is necessary to use the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty"><code>hasOwnProperty</code></a> method which all objects inherit from <code>Object.prototype</code>. To give you a concrete example, let's take the above graph example code to illustrate it:</p> - -<pre class="brush: js">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 -</pre> - -<p><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty"><code>hasOwnProperty</code></a> is the only thing in JavaScript which deals with properties and does <strong>not</strong> traverse the prototype chain.</p> - -<p>Note: It is <strong>not</strong> enough to check whether a property is <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined"><code>undefined</code></a>. The property might very well exist, but its value just happens to be set to <code>undefined</code>.</p> -</div> - -<h3 id="Bad_practice_Extension_of_native_prototypes">Bad practice: Extension of native prototypes</h3> - -<p>One misfeature that is often used is to extend <code>Object.prototype</code> or one of the other built-in prototypes.</p> - -<p>This technique is called monkey patching and breaks <em>encapsulation</em>. While used by popular frameworks such as Prototype.js, there is still no good reason for cluttering built-in types with additional <em>non-standard</em> functionality.</p> - -<p>The <strong>only</strong> good reason for extending a built-in prototype is to backport the features of newer JavaScript engines, like <code>Array.forEach</code>.</p> - -<h3 id="Summary_of_methods_for_extending_the_protoype_chain">Summary of methods for extending the protoype chain</h3> - -<p>Here are all 5 ways and their pros/cons. All of the examples listed below create exactly the same resulting <code>inst</code> object (thus logging the same results to the console), except in different ways for the purpose of illustration.</p> - -<table class="standard-table" style="text-align: top;"> - <tbody> - <tr> - <td style="width: 1%;">Name</td> - <td style="vertical-align: top; width: 1%;">Example(s)</td> - <td style="vertical-align: top;">Pro(s)</td> - <td style="vertical-align: top; width: 60%;">Con(s)</td> - </tr> - <tr> - <td>New-initialization</td> - <td style="vertical-align: top;"> - <pre class="brush: js"> -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); -</pre> - </td> - <td style="vertical-align: top;">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.</td> - <td style="vertical-align: top;">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.</td> - </tr> - <tr> - <td>Object.create</td> - <td style="vertical-align: top;"> - <pre class="brush: js"> -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); -</pre> - - <pre class="brush: js"> -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)</pre> - </td> - <td style="vertical-align: top;">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 <code>Object.create(null)</code>.</td> - <td style="vertical-align: top;">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.</td> - </tr> - <tr> - <td> - <p>Object.setPrototypeOf</p> - </td> - <td style="vertical-align: top;"> - <pre class="brush: js"> -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); -</pre> - - <pre class="brush: js"> -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)</pre> - </td> - <td style="vertical-align: top;">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 <code>Object.create(null)</code>.</td> - <td style="vertical-align: top;">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.</td> - </tr> - <tr> - <td>__proto__</td> - <td style="vertical-align: top;"> - <pre class="brush: js"> -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); -</pre> - - <pre class="brush: js"> -var inst = { - __proto__: { - bar_prop: "bar val", - __proto__: { - foo_prop: "foo val", - __proto__: Object - } - } -}; -console.log(inst.foo_prop); -console.log(inst.bar_prop)</pre> - </td> - <td style="vertical-align: top;">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.</td> - <td style="vertical-align: top;">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.</td> - </tr> - </tbody> -</table> - -<h2 id="prototype_and_Object.getPrototypeOf"><code>prototype</code> and <code>Object.getPrototypeOf</code></h2> - -<p>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.</p> - -<p>You probably already noticed that our <code>function A</code> has a special property called <code>prototype</code>. This special property works with the JavaScript <code>new </code>operator. The reference to the prototype object is copied to the internal <code>[[Prototype]]</code> property of the new instance. For example, when you do <code>var a1 = new A()</code>, JavaScript (after creating the object in memory and before running function <code>A()</code> with <code>this</code> defined to it) sets <code>a1.[[Prototype]] = A.prototype</code>. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in <code>[[Prototype]]</code>. This means that all the stuff you define in <code>prototype</code> is effectively shared by all instances, and you can even later change parts of <code>prototype</code> and have the changes appear in all existing instances, if you wanted to.</p> - -<p>If, in the example above, you do <code>var a1 = new A(); var a2 = new A();</code> then <code>a1.doSomething</code> would actually refer to <code>Object.getPrototypeOf(a1).doSomething</code>, which is the same as the <code>A.prototype.doSomething</code> you defined, i.e. <code>Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething</code>.</p> - -<p>In short, <code>prototype</code> is for types, while <code>Object.getPrototypeOf()</code> is the same for instances.</p> - -<p><code>[[Prototype]]</code> is looked at <em>recursively</em>, i.e. <code>a1.doSomething</code>, <code>Object.getPrototypeOf(a1).doSomething</code>, <code>Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething</code> etc., until it's found or <code>Object.getPrototypeOf </code>returns null.</p> - -<p>So, when you call</p> - -<pre class="brush: js">var o = new Foo();</pre> - -<p>JavaScript actually just does</p> - -<pre class="brush: js">var o = new Object(); -o.[[Prototype]] = Foo.prototype; -Foo.call(o);</pre> - -<p>(or something like that) and when you later do</p> - -<pre class="brush: js">o.someProp;</pre> - -<p>it checks whether <code>o</code> has a property <code>someProp</code>. If not, it checks <code>Object.getPrototypeOf(o).someProp</code>, and if that doesn't exist it checks <code>Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp</code>, and so on.</p> - -<h2 id="In_conclusion">In conclusion</h2> - -<p>It is <strong>essential</strong> 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 <strong>never</strong> be extended unless it is for the sake of compatibility with newer JavaScript features.</p> 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 ---- -<div>{{JsSidebar("Classes")}}</div> - -<p>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.</p> - -<h2 id="Defining_classes">Defining classes</h2> - -<p>Classes are in fact "special <a href="/en-US/docs/Web/JavaScript/Reference/Functions">functions</a>", and just as you can define <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expressions</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function declarations</a>, the class syntax has two components: <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">class expressions</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class declarations</a>.</p> - -<h3 id="Class_declarations">Class declarations</h3> - -<p>One way to define a class is using a <strong>class declaration</strong>. To declare a class, you use the <code>class</code> keyword with the name of the class ("Rectangle" here).</p> - -<pre class="brush: js notranslate">class Rectangle { - constructor(height, width) { - this.height = height; - this.width = width; - } -}</pre> - -<h4 id="Hoisting">Hoisting</h4> - -<p>An important difference between <strong>function declarations</strong> and <strong>class declarations</strong> is that function declarations are <a href="/en-US/docs/Glossary/Hoisting">hoisted</a> 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")}}:</p> - -<pre class="brush: js example-bad notranslate">const p = new Rectangle(); // ReferenceError - -class Rectangle {} -</pre> - -<h3 id="Class_expressions">Class expressions</h3> - -<p>A <strong>class expression</strong> 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).</p> - -<pre class="brush: js notranslate">// 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" -</pre> - -<div class="note"> -<p><strong>Note:</strong> Class <strong>expressions</strong> are subject to the same hoisting restrictions as described in the <a href="#Class_declarations">Class declarations</a> section.</p> -</div> - -<h2 id="Class_body_and_method_definitions">Class body and method definitions</h2> - -<p>The body of a class is the part that is in curly brackets <code>{}</code>. This is where you define class members, such as methods or constructor.</p> - -<h3 id="Strict_mode">Strict mode</h3> - -<p>The body of a class is executed in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, 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.</p> - -<h3 id="Constructor">Constructor</h3> - -<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor</a></code> method is a special method for creating and initializing an object created with a <code>class</code>. 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 <code>constructor</code> method.</p> - -<p>A constructor can use the <code>super</code> keyword to call the constructor of the super class.</p> - -<h3 id="Prototype_methods">Prototype methods</h3> - -<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>.</p> - -<pre class="brush: js notranslate">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</pre> - -<h3 id="Static_methods">Static methods</h3> - -<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> keyword defines a static method for a class. Static methods are called without <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)" title='An example of class instance is "var john = new Person();"'>instantiating </a>their class and <strong>cannot </strong>be called through a class instance. Static methods are often used to create utility functions for an application.</p> - -<pre class="brush: js notranslate">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 -</pre> - -<h3 id="Binding_this_with_prototype_and_static_methods">Binding <code>this</code> with prototype and static methods</h3> - -<p>When a static or prototype method is called without a value for <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, such as by assigning a variable to the method and then calling it, the <code>this</code> value will be <code>undefined</code> inside the method. This behavior will be the same even if the <code><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">"use strict"</a></code> directive isn't present, because code within the <code>class</code> body's syntactic boundary is always executed in strict mode.</p> - -<pre class="brush: js notranslate">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</pre> - -<p>If we rewrite the above using traditional function-based syntax in non–strict mode, then <code>this</code> method calls is automatically bound to the initial <code>this</code> value, which by default is the <a href="/en-US/docs/Glossary/Global_object">global object</a>. In strict mode, autobinding will not happen; the value of <code>this</code> remains as passed.</p> - -<pre class="brush: js notranslate">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) -</pre> - -<h3 id="Instance_properties">Instance properties</h3> - -<p>Instance properties must be defined inside of class methods:</p> - -<pre class="brush: js notranslate">class Rectangle { - constructor(height, width) { - this.height = height; - this.width = width; - } -}</pre> - -<p>Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:</p> - -<pre class="brush: js notranslate">Rectangle.staticWidth = 20; -Rectangle.prototype.prototypeWidth = 25; -</pre> - -<h3 id="Field_declarations">Field declarations</h3> - -<div class="warning"> -<p>Public and private field declarations are an <a href="https://github.com/tc39/proposal-class-fields">experimental feature (stage 3)</a> proposed at <a href="https://tc39.es">TC39</a>, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like <a href="https://babeljs.io/">Babel</a>.</p> -</div> - -<h4 id="Public_field_declarations">Public field declarations</h4> - -<p>With the JavaScript field declaration syntax, the above example can be written as:</p> - -<pre class="brush: js notranslate">class Rectangle { - height = 0; - width; - constructor(height, width) { - this.height = height; - this.width = width; - } -} -</pre> - -<p>By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.</p> - -<p>As seen above, the fields can be declared with or without a default value.</p> - -<p>See <a href="/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields">public class fields</a> for more information.</p> - -<h4 id="Private_field_declarations">Private field declarations</h4> - -<p>Using private fields, the definition can be refined as below.</p> - -<pre class="brush: js notranslate">class Rectangle { - #height = 0; - #width; - constructor(height, width) { - this.#height = height; - this.#width = width; - } -} -</pre> - -<p>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.</p> - -<div class="note"> -<p>Private fields can only be declared up-front in a field declaration.</p> -</div> - -<p>Private fields cannot be created later through assigning to them, the way that normal properties can.</p> - -<p>For more information, see <a href="/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields">private class fields</a>.</p> - -<h2 id="Sub_classing_with_extends">Sub classing with <code>extends</code></h2> - -<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> keyword is used in <em>class declarations</em> or <em>class expressions</em> to create a class as a child of another class.</p> - -<pre class="brush: js notranslate">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. -</pre> - -<p>If there is a constructor present in the subclass, it needs to first call super() before using "this".</p> - -<p>One may also extend traditional function-based "classes":</p> - -<pre class="brush: js notranslate">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</pre> - -<p>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()")}}:</p> - -<pre class="brush: js notranslate">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. -</pre> - -<h2 id="Species">Species</h2> - -<p>You might want to return {{jsxref("Array")}} objects in your derived array class <code>MyArray</code>. The species pattern lets you override default constructors.</p> - -<p>For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent <code>Array</code> object, instead of the <code>MyArray</code> object. The {{jsxref("Symbol.species")}} symbol lets you do this:</p> - -<pre class="brush: js notranslate">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 -</pre> - -<h2 id="Super_class_calls_with_super">Super class calls with <code>super</code></h2> - -<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code> keyword is used to call corresponding methods of super class. This is one advantage over prototype-based inheritance.</p> - -<pre class="brush: js notranslate">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. -</pre> - -<h2 id="Mix-ins">Mix-ins</h2> - -<p>Abstract subclasses or <em>mix-ins</em> 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.</p> - -<p>A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:</p> - -<pre class="brush: js notranslate">let calculatorMixin = Base => class extends Base { - calc() { } -}; - -let randomizerMixin = Base => class extends Base { - randomize() { } -}; -</pre> - -<p>A class that uses these mix-ins can then be written like this:</p> - -<pre class="brush: js notranslate">class Foo { } -class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.classes")}}</p> - -<h2 id="Re-running_a_class_definition">Re-running a class definition</h2> - -<p>A class can't be redefined. Attempting to do so produces a <code>SyntaxError</code>.</p> - -<p>If you're experimenting with code in a web browser, such as the Firefox Web Console (<strong>Tools </strong>><strong> Web Developer </strong>><strong> Web Console</strong>) and you 'Run' a definition of a class with the same name twice, you'll get a <code>SyntaxError: redeclaration of let <em>ClassName</em>;</code>. (See further discussion of this issue in <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1428672">bug 1428672</a>.) Doing something similar in Chrome Developer Tools gives you a message like <code>Uncaught SyntaxError: Identifier '<em>ClassName</em>' has already been declared at <anonymous>:1:1</code>.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields">Public class fields</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields">Private class fields</a></li> - <li>{{jsxref("Operators/super", "super")}}</li> - <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li> - <li><a href="https://github.com/tc39/proposal-class-fields">Fields and public/private class properties proposal (stage 3)</a></li> -</ul> 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 ---- -<p>{{jsSidebar("Errors")}}</p> - -<p>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 <code>name</code> and a <code>message</code>.</p> - -<p>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.</p> - -<h2 id="List_of_errors">List of errors</h2> - -<p>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!</p> - -<p>{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a>: Beginner's introductory tutorial on fixing JavaScript errors.</li> -</ul> 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 ---- -<div>{{jsSidebar("Errors")}}</div> - -<h2 id="Message">Message</h2> - -<pre class="syntaxbox">Error: Out of stack space (Edge) -InternalError: too much recursion (Firefox) -RangeError: Maximum call stack size exceeded (Chrome) -</pre> - -<h2 id="Error_type">Error type</h2> - -<p>{{jsxref("InternalError")}}.</p> - -<h2 id="What_went_wrong">What went wrong?</h2> - -<p>A function that calls itself is called a <em>recursive function</em>. Once a condition is met, the function stops calling itself. This is called a <em>base case</em>.</p> - -<p>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). <span class="seoSummary">When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.</span></p> - -<h2 id="Examples">Examples</h2> - -<p>This recursive function runs 10 times, as per the exit condition.</p> - -<pre class="brush: js">function loop(x) { - if (x >= 10) // "x >= 10" is the exit condition - return; - // do stuff - loop(x + 1); // the recursive call -} -loop(0);</pre> - -<p>Setting this condition to an extremely high value, won't work:</p> - -<pre class="brush: js example-bad">function loop(x) { - if (x >= 1000000000000) - return; - // do stuff - loop(x + 1); -} -loop(0); - -// InternalError: too much recursion</pre> - -<p>This recursive function is missing a base case. As there is no exit condition, the function will call itself infinitely.</p> - -<pre class="brush: js example-bad">function loop(x) { - // The base case is missing - -loop(x + 1); // Recursive call -} - -loop(0); - -// InternalError: too much recursion</pre> - -<h3 id="Class_error_too_much_recursion">Class error: too much recursion</h3> - -<pre class="brush: js example-bad">class Person{ - constructor(){} - set name(name){ - this.name = name; // Recursive call - } -} - - -const tony = new Person(); -tony.name = "Tonisha"; // InternalError: too much recursion -</pre> - -<p>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.</p> - -<pre class="brush: js example-bad">set name(name){ - this.name = name; // Recursive call -} -</pre> - -<div class="note"> -<p>In this example when the setter is triggered, it is told to do the same thing again: <em>to set the same property that it is meant to handle.</em> This causes the function to call itself, again and again, making it infinitely recursive.</p> -</div> - -<p>This issue also appears if the same variable is used in the getter.</p> - -<pre class="brush: js example-bad">get name(){ - return this.name; // Recursive call -} -</pre> - -<p>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.</p> - -<pre class="brush: js">class Person{ - constructor(){} - set name(name){ - this._name = name; - } - get name(){ - return this._name; - } -} -const tony = new Person(); -tony.name = "Tonisha"; -console.log(tony); -</pre> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{Glossary("Recursion")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Recursion">Recursive functions</a></li> -</ul> 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 ---- -<div class="twocolumns"> - -</div> - -<div class="threecolumns"> -<p>{{jsSidebar("Errors")}}</p> -</div> - -<p>The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.</p> - -<h2 id="Message">Message</h2> - -<pre class="syntaxbox notranslate">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" -</pre> - -<h2 id="Error_type">Error type</h2> - -<p>{{jsxref("SyntaxError")}}</p> - -<h2 id="What_went_wrong">What went wrong?</h2> - -<p>A specific language construct was expected, but something else was provided. This might be a simple typo.</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Expression_expected">Expression expected</h3> - -<p>For example, when chaining expressions, trailing commas are not allowed.</p> - -<pre class="brush: js example-bad notranslate">for (let i = 0; i < 5,; ++i) { - console.log(i); -} -// SyntaxError: expected expression, got ')' -</pre> - -<p>Correct would be omitting the comma or adding another expression:</p> - -<pre class="brush: js example-good notranslate">for (let i = 0; i < 5; ++i) { - console.log(i); -} -</pre> - -<h3 id="Not_enough_brackets">Not enough brackets</h3> - -<p>Sometimes, you leave out brackets around <code>if</code> statements:</p> - -<pre class="brush: js example-bad line-numbers language-js notranslate">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 '||'</pre> - -<p>The brackets may look correct at first, but note how the <code>||</code> is outside the brackets. Correct would be putting brackets around the <code>||</code>:</p> - -<pre class="brush: js example-good notranslate">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; - } -} -</pre> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("SyntaxError")}}</li> -</ul> 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 ---- -<div>{{jsSidebar("Functions")}}</div> - -<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> 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 <em>function body</em>. Values can be <em>passed</em> to a function, and the function will <em>return</em> a value.</p> - -<p>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 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a></code> objects.</p> - -<p>For more examples and explanations, see also the <a href="/en-US/docs/Web/JavaScript/Guide/Functions">JavaScript guide about functions</a>.</p> - -<h2 id="Description">Description</h2> - -<p>Every function in JavaScript is a <code>Function</code> object. See {{jsxref("Function")}} for information on properties and methods of <code>Function</code> objects.</p> - -<p>To return a value other than the default, a function must have a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a></code> statement that specifies the value to return. A function without a return statement will return a default value. In the case of a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> called with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code> keyword, the default value is the value of its <code>this</code> parameter. For all other functions, the default return value is {{jsxref("undefined")}}.</p> - -<p>The parameters of a function call are the function's <em>arguments</em>. Arguments are passed to functions <em>by value</em>. 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:</p> - -<pre class="brush: js">/* 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); -</pre> - -<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> keyword</a> does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body.</p> - -<h2 id="Defining_functions">Defining functions</h2> - -<p>There are several ways to define functions:</p> - -<h3 id="The_function_declaration_(function_statement)">The function declaration (<code>function</code> statement)</h3> - -<p>There is a special syntax for declaring functions (see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> for details):</p> - -<pre class="syntaxbox">function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { - <em>statements</em> -} -</pre> - -<dl> - <dt><code>name</code></dt> - <dd>The function name.</dd> -</dl> - -<dl> - <dt><code>param</code></dt> - <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> -</dl> - -<dl> - <dt><code>statements</code></dt> - <dd>The statements comprising the body of the function.</dd> -</dl> - -<h3 id="The_function_expression_(function_expression)">The function expression (<code>function</code> expression)</h3> - -<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> 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 <em>hoisted</em> onto the beginning of the scope, therefore they cannot be used before they appear in the code.</p> - -<pre class="syntaxbox">function [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { - <em>statements</em> -} -</pre> - -<dl> - <dt><code>name</code></dt> - <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> -</dl> - -<dl> - <dt><code>param</code></dt> - <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> - <dt><code>statements</code></dt> - <dd>The statements comprising the body of the function.</dd> -</dl> - -<p>Here is an example of an <strong>anonymous</strong> function expression (the <code>name</code> is not used):</p> - -<pre class="brush: js">var myFunction = function() { - statements -}</pre> - -<p>It is also possible to provide a name inside the definition in order to create a <strong>named</strong> function expression:</p> - -<pre class="brush: js">var myFunction = function namedFunction(){ - statements -} -</pre> - -<p>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.</p> - -<p>As we can see, both examples do not start with the <code>function</code> keyword. Statements involving functions which do not start with <code>function</code> are function expressions.</p> - -<p>When functions are used only once, a common pattern is an <strong>IIFE (<em>Immediately Invokable Function Expression</em>)</strong>.</p> - -<pre class="brush: js">(function() { - statements -})();</pre> - -<p>IIFE are function expressions that are invoked as soon as the function is declared.</p> - -<h3 id="The_generator_function_declaration_(function*_statement)">The generator function declaration (<code>function*</code> statement)</h3> - -<p>There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):</p> - -<pre class="syntaxbox">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { - <em>statements</em> -} -</pre> - -<dl> - <dt><code>name</code></dt> - <dd>The function name.</dd> -</dl> - -<dl> - <dt><code>param</code></dt> - <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> -</dl> - -<dl> - <dt><code>statements</code></dt> - <dd>The statements comprising the body of the function.</dd> -</dl> - -<h3 id="The_generator_function_expression_(function*_expression)">The generator function expression (<code>function*</code> expression)</h3> - -<p>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):</p> - -<pre class="syntaxbox">function* [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { - <em>statements</em> -} -</pre> - -<dl> - <dt><code>name</code></dt> - <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> -</dl> - -<dl> - <dt><code>param</code></dt> - <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> - <dt><code>statements</code></dt> - <dd>The statements comprising the body of the function.</dd> -</dl> - -<h3 id="The_arrow_function_expression_(>)">The arrow function expression (=>)</h3> - -<p>An arrow function expression has a shorter syntax and lexically binds its <code>this</code> value (see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> for details):</p> - -<pre class="syntaxbox">([param[, param]]) => { - statements -} - -param => expression -</pre> - -<dl> - <dt><code>param</code></dt> - <dd>The name of an argument. Zero arguments need to be indicated with <code>()</code>. For only one argument, the parentheses are not required. (like <code>foo => 1</code>)</dd> - <dt><code>statements or expression</code></dt> - <dd>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.</dd> -</dl> - -<h3 id="The_Function_constructor">The <code>Function</code> constructor</h3> - -<div class="note"> -<p><strong>Note:</strong> Using the <code>Function</code> 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.</p> -</div> - -<p>As all other objects, {{jsxref("Function")}} objects can be created using the <code>new</code> operator:</p> - -<pre class="syntaxbox">new Function (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) -</pre> - -<dl> - <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> - <dd>Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.</dd> -</dl> - -<dl> - <dt><code>functionBody</code></dt> - <dd>A string containing the JavaScript statements comprising the function body.</dd> -</dl> - -<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> - -<h3 id="The_GeneratorFunction_constructor">The <code>GeneratorFunction</code> constructor</h3> - -<div class="note"> -<p><strong>Note:</strong> <code>GeneratorFunction</code> is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).</p> -</div> - -<div class="note"> -<p><strong>Note:</strong> Using the <code>GeneratorFunction</code> 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.</p> -</div> - -<p>As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the <code>new</code> operator:</p> - -<pre class="syntaxbox">new GeneratorFunction (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) -</pre> - -<dl> - <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> - <dd>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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> -</dl> - -<dl> - <dt><code>functionBody</code></dt> - <dd>A string containing the JavaScript statements comprising the function definition.</dd> -</dl> - -<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> - -<h2 id="Function_parameters">Function parameters</h2> - -<h3 id="Default_parameters">Default parameters</h3> - -<p>Default function parameters allow formal parameters to be initialized with default values if no value or <code>undefined</code> is passed. For more details, see<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters"> default parameters</a>.</p> - -<h3 id="Rest_parameters">Rest parameters</h3> - -<p>The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p> - -<h2 id="The_arguments_object">The <code>arguments</code> object</h2> - -<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>.</p> - -<ul> - <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments">arguments</a></code>: An array-like object containing the arguments passed to the currently executing function.</li> - <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a></code> {{Deprecated_inline}}: The currently executing function.</li> - <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a></code> {{Obsolete_inline}} : The function that invoked the currently executing function.</li> - <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code>: The number of arguments passed to the function.</li> -</ul> - -<h2 id="Defining_method_functions">Defining method functions</h2> - -<h3 id="Getter_and_setter_functions">Getter and setter functions</h3> - -<p>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.</p> - -<dl> - <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></dt> - <dd> - <p>Binds an object property to a function that will be called when that property is looked up.</p> - </dd> - <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></dt> - <dd>Binds an object property to a function to be called when there is an attempt to set that property.</dd> -</dl> - -<h3 id="Method_definition_syntax">Method definition syntax</h3> - -<p>Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a> for more information.</p> - -<pre class="brush: js">var obj = { - foo() {}, - bar() {} -};</pre> - -<h2 id="Function_constructor_vs._function_declaration_vs._function_expression"><code>Function</code> constructor vs. function declaration vs. function expression</h2> - -<p>Compare the following:</p> - -<p>A function defined with the <code>Function</code> constructor assigned to the variable <code>multiply:</code></p> - -<pre class="brush: js">var multiply = new Function('x', 'y', 'return x * y');</pre> - -<p>A <em>function declaration</em> of a function named <code>multiply</code>:</p> - -<pre class="brush: js">function multiply(x, y) { - return x * y; -} // there is no semicolon here -</pre> - -<p>A <em>function expression</em> of an anonymous function assigned to the variable <code>multiply:</code></p> - -<pre class="brush: js">var multiply = function(x, y) { - return x * y; -}; -</pre> - -<p>A <em>function expression</em> of a function named <code>func_name</code> assigned to the variable <code>multiply:</code></p> - -<pre class="brush: js">var multiply = function func_name(x, y) { - return x * y; -}; -</pre> - -<h3 id="Differences">Differences</h3> - -<p>All do approximately the same thing, with a few subtle differences:</p> - -<p>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 <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example:</p> - -<pre class="brush: js">var y = function x() {}; -alert(x); // throws an error -</pre> - -<p>The function name also appears when the function is serialized via <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p> - -<p>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.</p> - -<p>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:</p> - -<p>A function defined by '<code>new Function'</code> does not have a function name. However, in the <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs:</p> - -<pre class="brush: js">function anonymous() { -} -</pre> - -<p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p> - -<pre class="brush: js">var foo = new Function("alert(anonymous);"); -foo(); -</pre> - -<p>Unlike functions defined by function expressions or by the <code>Function</code> constructor, a function defined by a function declaration can be used before the function declaration itself. For example:</p> - -<pre class="brush: js">foo(); // alerts FOO! -function foo() { - alert('FOO!'); -} -</pre> - -<p>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 <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</p> - -<pre class="brush: js">/* - * 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) - */ -</pre> - -<p>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> 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 "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should generally be avoided whenever possible.</p> - -<p>It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a <code>Function constructor</code> 's string aren't parsed repeatedly. For example:</p> - -<pre class="brush: js">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.</pre> - -<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p> - -<ul> - <li>becomes part of an expression</li> - <li>is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:</li> -</ul> - -<pre class="brush: js">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 - } -} -</pre> - -<h3 id="Examples">Examples</h3> - -<pre class="brush: js">// 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() {} - } -} -</pre> - -<h2 id="Block-level_functions">Block-level functions</h2> - -<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.</p> - -<pre class="brush: js">'use strict'; - -function f() { - return 1; -} - -{ - function f() { - return 2; - } -} - -f() === 1; // true - -// f() === 2 in non-strict mode -</pre> - -<h3 id="Block-level_functions_in_non-strict_code">Block-level functions in non-strict code</h3> - -<p>In a word: Don't.</p> - -<p>In non-strict code, function declarations inside blocks behave strangely. For example:</p> - -<pre class="brush: js">if (shouldDefineZero) { - function zero() { // DANGER: compatibility risk - console.log("This is zero."); - } -} -</pre> - -<p>ES2015 says that if <code>shouldDefineZero</code> is false, then <code>zero</code> 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 <code>zero</code> whether the block executed or not.</p> - -<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, all browsers that support ES2015 handle this the same way: <code>zero</code> is defined only if <code>shouldDefineZero</code> is true, and only in the scope of the <code>if</code>-block.</p> - -<p>A safer way to define functions conditionally is to assign a function expression to a variable:</p> - -<pre class="brush: js">var zero; -if (shouldDefineZero) { - zero = function() { - console.log("This is zero."); - }; -} -</pre> - -<h2 id="Examples_2">Examples</h2> - -<h3 id="Returning_a_formatted_number">Returning a formatted number</h3> - -<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p> - -<pre class="brush: js">// 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; -} -</pre> - -<p>The following statements call the padZeros function.</p> - -<pre class="brush: js">var result; -result = padZeros(42,4); // returns "0042" -result = padZeros(42,2); // returns "42" -result = padZeros(5,4); // returns "0005" -</pre> - -<h3 id="Determining_whether_a_function_exists">Determining whether a function exists</h3> - -<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is performed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p> - -<pre class="brush: js"> if ('function' === typeof window.noFunc) { - // use noFunc() - } else { - // do something else - } -</pre> - -<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>New: Arrow functions, Generator functions, default parameters, rest parameters.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.functions")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Statements/function", "function statement")}}</li> - <li>{{jsxref("Operators/function", "function expression")}}</li> - <li>{{jsxref("Statements/function*", "function* statement")}}</li> - <li>{{jsxref("Operators/function*", "function* expression")}}</li> - <li>{{jsxref("Function")}}</li> - <li>{{jsxref("GeneratorFunction")}}</li> - <li>{{jsxref("Functions/Arrow_functions", "Arrow functions")}}</li> - <li>{{jsxref("Functions/Default_parameters", "Default parameters")}}</li> - <li>{{jsxref("Functions/rest_parameters", "Rest parameters")}}</li> - <li>{{jsxref("Functions/arguments", "Arguments object")}}</li> - <li>{{jsxref("Functions/get", "getter")}}</li> - <li>{{jsxref("Functions/set", "setter")}}</li> - <li>{{jsxref("Functions/Method_definitions", "Method definitions")}}</li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">Functions and function scope</a></li> -</ul> 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 ---- -<div>{{JSRef}}</div> - -<div dir="rtl">شیء <strong><code>Array</code></strong> در جاوااسکریپت یک شیء عمومی است که در ساخت آرایه ها استفاده می شود که اشیائی سطح بالا شبیه فهرست هستند.</div> - -<div dir="rtl"></div> - -<p dir="rtl"><strong>ساخت یک آرایه</strong></p> - -<pre class="brush: js">var fruits = ['Apple', 'Banana']; - -console.log(fruits.length); -// 2 -</pre> - -<p dir="rtl"><strong>دسترسی به یک آیتم در آرایه (بر اساس نمایه)</strong></p> - -<pre class="brush: js">var first = fruits[0]; -// Apple - -var last = fruits[fruits.length - 1]; -// Banana -</pre> - -<p dir="rtl"><strong>اجرای حلقه روی آرایه</strong></p> - -<pre class="brush: js">fruits.forEach(function(item, index, array) { - console.log(item, index); -}); -// Apple 0 -// Banana 1 -</pre> - -<p dir="rtl"><strong>اضافه کردن به انتهای آرایه</strong></p> - -<pre class="brush: js">var newLength = fruits.push('Orange'); -// ["Apple", "Banana", "Orange"] -</pre> - -<p dir="rtl"><strong>حذف کردن از انتهای آرایه</strong></p> - -<pre class="brush: js">var last = fruits.pop(); // remove Orange (from the end) -// ["Apple", "Banana"]; -</pre> - -<p dir="rtl"><strong>حذف کردن از ابتدای آرایه</strong></p> - -<pre class="brush: js">var first = fruits.shift(); // remove Apple from the front -// ["Banana"]; -</pre> - -<p dir="rtl"><strong>اضافه کردن به ابتدای آرایه</strong></p> - -<pre class="brush: js">var newLength = fruits.unshift('Strawberry') // add to the front -// ["Strawberry", "Banana"]; -</pre> - -<p dir="rtl"><strong>پیدا کردن نمایه یک آیتم در یک آرایه</strong></p> - -<pre class="brush: js">fruits.push('Mango'); -// ["Strawberry", "Banana", "Mango"] - -var pos = fruits.indexOf('Banana'); -// 1 -</pre> - -<p dir="rtl"><strong>پاک کردن یک آیتم بر اساس موقعیت نمایه</strong></p> - -<pre class="brush: js">var removedItem = fruits.splice(pos, 1); // this is how to remove an item - -// ["Strawberry", "Mango"]</pre> - -<p dir="rtl"><strong>پاک کردن آیتم ها بر اساس موقعیت نمایه</strong></p> - -<pre class="brush: js">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"]</pre> - -<p dir="rtl"><strong>کپی کردن یک آرایه</strong></p> - -<pre class="brush: js">var shallowCopy = fruits.slice(); // this is how to make a copy -// ["Strawberry", "Mango"] -</pre> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">[<var>element0</var>, <var>element1</var>, ..., <var>elementN</var>] -new Array(<var>element0</var>, <var>element1</var>[, ...[, <var>elementN</var>]]) -new Array(<var>arrayLength</var>)</pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>element<em>N</em></code></dt> - <dd>A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the <code>Array</code> 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 <code>Array</code> constructor, not array literals created with the bracket syntax.</dd> - <dt><code>arrayLength</code></dt> - <dd>If the only argument passed to the <code>Array</code> constructor is an integer between 0 and 2<sup>32</sup>-1 (inclusive), this returns a new JavaScript array with its <code>length</code> property set to that number (<strong>Note:</strong> this implies an array of <code>arrayLength</code> empty slots, not slots with actual <code>undefined</code> values). If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.</dd> -</dl> - -<h2 id="Description">Description</h2> - -<p>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.</p> - -<p>Arrays cannot use strings as element indexes (as in an <a href="https://en.wikipedia.org/wiki/Associative_array">associative array</a>) but must use integers. Setting or accessing via non-integers using <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties">bracket notation</a> (or <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">dot notation</a>) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's <a href="/en-US/docs/Web/JavaScript/Data_structures#Properties">object property collection</a>. The array's object properties and list of array elements are separate, and the array's <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_methods">traversal and mutation operations</a> cannot be applied to these named properties.</p> - -<h3 id="Accessing_array_elements">Accessing array elements</h3> - -<p>JavaScript arrays are zero-indexed: the first element of an array is at index <code>0</code>, 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 <code>undefined</code>.</p> - -<pre class="brush: js">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' -</pre> - -<p>Array elements are object properties in the same way that <code>toString</code> 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:</p> - -<pre class="brush: js">console.log(arr.0); // a syntax error -</pre> - -<p>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 <code>'3d'</code>, it can only be referenced using bracket notation. E.g.:</p> - -<pre class="brush: js">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; -console.log(years.0); // a syntax error -console.log(years[0]); // works properly -</pre> - -<pre class="brush: js">renderer.3d.setTexture(model, 'character.png'); // a syntax error -renderer['3d'].setTexture(model, 'character.png'); // works properly -</pre> - -<p>Note that in the <code>3d</code> example, <code>'3d'</code> had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., <code>years['2']</code> instead of <code>years[2]</code>), although it's not necessary. The 2 in <code>years[2]</code> is coerced into a string by the JavaScript engine through an implicit <code>toString</code> conversion. It is, for this reason, that <code>'2'</code> and <code>'02'</code> would refer to two different slots on the <code>years</code> object and the following example could be <code>true</code>:</p> - -<pre class="brush: js">console.log(years['2'] != years['02']); -</pre> - -<p>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):</p> - -<pre class="brush: js">var promise = { - 'var' : 'text', - 'array': [1, 2, 3, 4] -}; - -console.log(promise['var']); -</pre> - -<h3 id="Relationship_between_length_and_numerical_properties">Relationship between <code>length</code> and numerical properties</h3> - -<p>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.</p> - -<pre class="brush: js">var fruits = []; -fruits.push('banana', 'apple', 'peach'); - -console.log(fruits.length); // 3 -</pre> - -<p>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:</p> - -<pre class="brush: js">fruits[5] = 'mango'; -console.log(fruits[5]); // 'mango' -console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] -console.log(fruits.length); // 6 -</pre> - -<p>Increasing the {{jsxref("Array.length", "length")}}.</p> - -<pre class="brush: js">fruits.length = 10; -console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] -console.log(fruits.length); // 10 -</pre> - -<p>Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.</p> - -<pre class="brush: js">fruits.length = 2; -console.log(Object.keys(fruits)); // ['0', '1'] -console.log(fruits.length); // 2 -</pre> - -<p>This is explained further on the {{jsxref("Array.length")}} page.</p> - -<h3 id="Creating_an_array_using_the_result_of_a_match">Creating an array using the result of a match</h3> - -<p>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:</p> - -<pre class="brush: js">// 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'); -</pre> - -<p>The properties and elements returned from this match are as follows:</p> - -<table class="fullwidth-table"> - <tbody> - <tr> - <td class="header">Property/Element</td> - <td class="header">Description</td> - <td class="header">Example</td> - </tr> - <tr> - <td><code>input</code></td> - <td>A read-only property that reflects the original string against which the regular expression was matched.</td> - <td>cdbBdbsbz</td> - </tr> - <tr> - <td><code>index</code></td> - <td>A read-only property that is the zero-based index of the match in the string.</td> - <td>1</td> - </tr> - <tr> - <td><code>[0]</code></td> - <td>A read-only element that specifies the last matched characters.</td> - <td>dbBd</td> - </tr> - <tr> - <td><code>[1], ...[n]</code></td> - <td>Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.</td> - <td>[1]: bB<br> - [2]: d</td> - </tr> - </tbody> -</table> - -<h2 id="Properties">Properties</h2> - -<dl> - <dt><code>Array.length</code></dt> - <dd>The <code>Array</code> constructor's length property whose value is 1.</dd> - <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> - <dd>The constructor function that is used to create derived objects.</dd> - <dt>{{jsxref("Array.prototype")}}</dt> - <dd>Allows the addition of properties to all array objects.</dd> -</dl> - -<h2 id="Methods">Methods</h2> - -<dl> - <dt>{{jsxref("Array.from()")}}</dt> - <dd>Creates a new <code>Array</code> instance from an array-like or iterable object.</dd> - <dt>{{jsxref("Array.isArray()")}}</dt> - <dd>Returns true if a variable is an array, if not false.</dd> - <dt>{{jsxref("Array.of()")}}</dt> - <dd>Creates a new <code>Array</code> instance with a variable number of arguments, regardless of number or type of the arguments.</dd> -</dl> - -<h2 id="Array_instances"><code>Array</code> instances</h2> - -<p>All <code>Array</code> instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the <code>Array</code> constructor can be modified to affect all <code>Array</code> instances.</p> - -<h3 id="Properties_2">Properties</h3> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> - -<h3 id="Methods_2">Methods</h3> - -<h4 id="Mutator_methods">Mutator methods</h4> - -<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> - -<h4 id="Accessor_methods">Accessor methods</h4> - -<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> - -<h4 id="Iteration_methods">Iteration methods</h4> - -<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}</div> - -<h2 id="Array_generic_methods"><code>Array</code> generic methods</h2> - -<div class="warning"> -<p><strong>Array generics are non-standard, deprecated and will get removed in the near future</strong>.</p> -</div> - -<p>{{Obsolete_Header("Gecko71")}}</p> - -<p>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 <var>str</var> is a letter, you would write:</p> - -<pre class="brush: js">function isLetter(character) { - return character >= 'a' && character <= 'z'; -} - -if (Array.prototype.every.call(str, isLetter)) { - console.log("The string '" + str + "' contains only letters!"); -} -</pre> - -<p>This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:</p> - -<pre class="brush: js">if (Array.every(str, isLetter)) { - console.log("The string '" + str + "' contains only letters!"); -} -</pre> - -<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.</p> - -<p>These are <strong>not</strong> 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:</p> - -<pre class="brush: js">if (Array.from(str).every(isLetter)) { - console.log("The string '" + str + "' contains only letters!"); -} -</pre> - -<h2 id="Examples">Examples</h2> - -<h3 id="Creating_an_array">Creating an array</h3> - -<p>The following example creates an array, <code>msgArray</code>, with a length of 0, then assigns values to <code>msgArray[0]</code> and <code>msgArray[99]</code>, changing the length of the array to 100.</p> - -<pre class="brush: js">var msgArray = []; -msgArray[0] = 'Hello'; -msgArray[99] = 'world'; - -if (msgArray.length === 100) { - console.log('The length is 100.'); -} -</pre> - -<h3 id="Creating_a_two-dimensional_array">Creating a two-dimensional array</h3> - -<p>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.</p> - -<pre class="brush: js">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')); -</pre> - -<p>Here is the output:</p> - -<pre class="eval">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 -</pre> - -<h3 id="Using_an_array_to_tabulate_a_set_of_values">Using an array to tabulate a set of values</h3> - -<pre class="brush: js">values = []; -for (var x = 0; x < 10; x++){ - values.push([ - 2 ** x, - 2 * x ** 2 - ]) -}; -console.table(values)</pre> - -<p>Results in</p> - -<pre class="eval">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</pre> - -<p>(First column is the (index))</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4', 'Array')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>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")}}</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array-objects', 'Array')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>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")}}</td> - </tr> - <tr> - <td>{{SpecName('ES7', '#sec-array-objects', 'Array')}}</td> - <td>{{Spec2('ES7')}}</td> - <td>New method added: {{jsxref("Array.prototype.includes()")}}</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("javascript.builtins.Array")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> - <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_object">JavaScript Guide: “Indexed collections: <code>Array</code> object”</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> - <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> - <li><a href="/en-US/docs/JavaScript_typed_arrays">Typed Arrays</a></li> -</ul> 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 ---- -<div>{{JSRef}}</div> - -<div>متد Array.of() یک آرایه ی جدید شامل آرگومان های ارسال شده به آن میباشد میسازد، صرفنظر از تعداد و نوع آرگومان ها. </div> - -<p>تفاوت متد Array.of() و متد سازنده ی Array() در این میباشد که Array.of(7) یک آرایه با یک المنت که مقدارش 7 میباشد میسازد. در حالیکه Array(7) یک آرایه ی جدید با طول 7 که شامل 7 المنت یا slot با مقدار empty میسازد نه با مقدار undefined.</p> - -<pre class="brush: js">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] -</pre> - -<h2 id="نحوه_استفاده">نحوه استفاده</h2> - -<pre class="syntaxbox">Array.of(<var>element0</var>[, <var>element1</var>[, ...[, <var>elementN</var>]]])</pre> - -<h3 id="پارامترها">پارامترها</h3> - -<dl> - <dt><code>element<em>N</em></code></dt> - <dd>لیست المنت هایی که باید درون آرایه قرار بگیرند.</dd> -</dl> - -<h3 id="مقدار_بازگشتی">مقدار بازگشتی</h3> - -<p>یک نمونه جدید از {{jsxref("Array")}} .</p> - -<h2 id="توضیحات">توضیحات</h2> - -<p>این تابع بخشی از ECMAScript 2015 استاندارد است. برای اطلاعات بیشتر لینک های زیر مراجعه کنید:</p> - -<p dir="ltr"><a href="https://gist.github.com/rwaldron/1074126"><code>Array.of</code></a> و <a href="https://gist.github.com/rwaldron/1074126"><code>Array.from</code> proposal</a> و <a href="https://gist.github.com/rwaldron/3186576"><code>Array.of</code> polyfill</a>.</p> - -<h2 id="مثال">مثال</h2> - -<pre class="brush: js">Array.of(1); // [1] -Array.of(1, 2, 3); // [1, 2, 3] -Array.of(undefined); // [undefined] -</pre> - -<h2 id="چند_کاره_سازی">چند کاره سازی</h2> - -<p>در صورت عدم وجود <code>Array.of()</code> به صورت پیشفرض، با اجرای کد زیر قبل اجرای سایر کدها، تابع <code>Array.of()</code> را برای شما در کلاس Array پیاده سازی و قابل استفاده می نماید. برید حالشو ببرید.</p> - -<pre class="brush: js">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; - } -} -</pre> - -<h2 id="مشخصه_ها">مشخصه ها</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">مشخصه</th> - <th scope="col">وضعیت</th> - <th scope="col">توضیح</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}</td> - <td>{{Spec2('ES2015')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="سازگاری_با_سایر_مرورگرها">سازگاری با سایر مرورگرها</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.of")}}</p> -</div> - -<h2 id="همچنین_ببینید"><strong>همچنین ببینید</strong></h2> - -<ul> - <li>{{jsxref("Array")}}</li> - <li>{{jsxref("Array.from()")}}</li> - <li>{{jsxref("TypedArray.of()")}}</li> -</ul> 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 ---- -<div>{{JSRef}}</div> - -<p> The <code><strong>reduce()</strong></code> method executes a <strong>reducer</strong> function (that you provide) on each element of the array, resulting in a single output value.</p> - -<p style="direction: rtl;">متد reduce یک تابع reducer (کاهش دهنده) را بر روی هر کدام از المانهای آرایه اجرا میکند و در خروجی یک آرایه برمیگرداند. توجه داشته باشید که تابع reducer را شما باید بنویسید.</p> - -<div style="direction: rtl;">{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div> - - - -<p style="direction: rtl;">یک تابع کاهش دهنده 4 آرگومان دریافت میکند</p> - -<p>The <strong>reducer</strong> function takes four arguments:</p> - -<ol> - <li>Accumulator (acc) (انباشت کننده)</li> - <li>Current Value (cur) (مقدار فعلی)</li> - <li>Current Index (idx) (اندیس فعلی)</li> - <li>Source Array (src) (آرایهی مبدا)</li> -</ol> - -<p>Your <strong>reducer</strong> 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.</p> - -<p style="direction: rtl;">بنابراین آرگومان اول تابع reduce، کاهش دهنده، و آرگومان دوم، انباشتگر میباشد. به این ترتیب پس از اعمال کاهش دهنده بر روی هر کدام از المانهای آرایه، انباشت کننده یا اکیومیولیتور نیز اعمال اثر میکند.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><var>arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])</var></pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>callback</code></dt> - <dd>A function to execute on each element in the array (except for the first, if no <code>initialValue</code> is supplied), taking four arguments: - <dl> - <dt><code>accumulator</code></dt> - <dd>The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback, or <code>initialValue</code>, if supplied (see below).</dd> - <dt><code>currentValue</code></dt> - <dd>The current element being processed in the array.</dd> - <dt><code>index</code> {{optional_inline}}</dt> - <dd>The index of the current element being processed in the array. Starts from index 0 if an <code>initialValue</code> is provided. Otherwise, starts from index 1.</dd> - <dt><code>array</code> {{optional_inline}}</dt> - <dd>The array <code>reduce()</code> was called upon.</dd> - </dl> - </dd> - <dt><code>initialValue</code> {{optional_inline}}</dt> - <dd>A value to use as the first argument to the first call of the <code>callback</code>. If no <code>initialValue</code> is supplied, the first element in the array will be used and skipped. Calling <code>reduce()</code> on an empty array without an <code>initialValue</code> will throw a <code>TypeError</code>.</dd> -</dl> - -<h3 id="Return_value">Return value</h3> - -<p>The single value that results from the reduction.</p> - -<p style="direction: rtl;">مقدار بازگشتی مقداری واحد است.</p> - -<h2 id="Description">Description</h2> - -<p>The <code>reduce()</code> method executes the <code>callback</code> once for each assigned value present in the array, taking four arguments:</p> - -<p style="direction: rtl;">تابع reduce، کال بک را یک بار بر روی مقدارهای الصاق شده در ارایه اعمال می کند و چهار ارگومان (ورودی) زیر را می پذیرد.</p> - -<ul> - <li><code>accumulator</code></li> - <li><code>currentValue</code></li> - <li><code>currentIndex</code></li> - <li><code>array</code></li> -</ul> - -<p>The first time the callback is called, <code>accumulator</code> and <code>currentValue</code> can be one of two values. If <code>initialValue</code> is provided in the call to <code>reduce()</code>, then <code>accumulator</code> will be equal to <code>initialValue</code>, and <code>currentValue</code> will be equal to the first value in the array. If no <code>initialValue</code> is provided, then <code>accumulator</code> will be equal to the first value in the array, and <code>currentValue</code> will be equal to the second.</p> - -<div class="note"> -<p><strong>Note:</strong> If <code>initialValue</code> is not provided, <code>reduce()</code> will execute the callback function starting at index 1, skipping the first index. If <code>initialValue</code> is provided, it will start at index 0.</p> -</div> - -<p>If the array is empty and no <code>initialValue</code> is provided, {{jsxref("TypeError")}} will be thrown. If the array only has one element (regardless of position) and no <code>initialValue</code> is provided, or if <code>initialValue</code> is provided but the array is empty, the solo value will be returned <em>without </em>calling<em> <code>callback</code>.</em></p> - -<p>It is usually safer to provide an <code>initialValue</code> because there are three possible outputs without <code>initialValue</code>, as shown in the following example.</p> - -<p style="direction: rtl;">برای احتیاط بهتر است که همیشه یک initialValue یا مقدار اولیه درنظر گرفت زیرا در صورت در نظر نگرفتن مقدار اولیه سه حالت ممکن است رخ دهد که در مثال زیر توضیح داده شده است.</p> - -<pre class="brush: js">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 ); -</pre> - -<h3 id="How_reduce_works">How reduce() works</h3> - -<p>Suppose the following use of <code>reduce()</code> occurred:</p> - -<pre class="brush: js">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { - return accumulator + currentValue; -}); -</pre> - -<p>The callback would be invoked four times, with the arguments and return values in each call being as follows:</p> - -<table> - <thead> - <tr> - <th scope="col"><code>callback</code></th> - <th scope="col"><code>accumulator</code></th> - <th scope="col"><code>currentValue</code></th> - <th scope="col"><code>currentIndex</code></th> - <th scope="col"><code>array</code></th> - <th scope="col">return value</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">first call</th> - <td><code>0</code></td> - <td><code>1</code></td> - <td><code>1</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>1</code></td> - </tr> - <tr> - <th scope="row">second call</th> - <td><code>1</code></td> - <td><code>2</code></td> - <td><code>2</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>3</code></td> - </tr> - <tr> - <th scope="row">third call</th> - <td><code>3</code></td> - <td><code>3</code></td> - <td><code>3</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>6</code></td> - </tr> - <tr> - <th scope="row">fourth call</th> - <td><code>6</code></td> - <td><code>4</code></td> - <td><code>4</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>10</code></td> - </tr> - </tbody> -</table> - -<p>The value returned by <code>reduce()</code> would be that of the last callback invocation (<code>10</code>).</p> - -<p>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:</p> - -<pre class="brush: js">[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue ); -</pre> - -<p>If you were to provide an <code>initialValue</code> as the second argument to <code>reduce()</code>, the result would look like this:</p> - -<pre class="brush: js">[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { - return accumulator + currentValue; -}, 10); -</pre> - -<table> - <thead> - <tr> - <th scope="col"><code>callback</code></th> - <th scope="col"><code>accumulator</code></th> - <th scope="col"><code>currentValue</code></th> - <th scope="col"><code>currentIndex</code></th> - <th scope="col"><code>array</code></th> - <th scope="col">return value</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row">first call</th> - <td><code>10</code></td> - <td><code>0</code></td> - <td><code>0</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>10</code></td> - </tr> - <tr> - <th scope="row">second call</th> - <td><code>10</code></td> - <td><code>1</code></td> - <td><code>1</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>11</code></td> - </tr> - <tr> - <th scope="row">third call</th> - <td><code>11</code></td> - <td><code>2</code></td> - <td><code>2</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>13</code></td> - </tr> - <tr> - <th scope="row">fourth call</th> - <td><code>13</code></td> - <td><code>3</code></td> - <td><code>3</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>16</code></td> - </tr> - <tr> - <th scope="row">fifth call</th> - <td><code>16</code></td> - <td><code>4</code></td> - <td><code>4</code></td> - <td><code>[0, 1, 2, 3, 4]</code></td> - <td><code>20</code></td> - </tr> - </tbody> -</table> - -<p>The value returned by <code>reduce()</code> in this case would be <code>20</code>.</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Sum_all_the_values_of_an_array">Sum all the values of an array</h3> - -<pre class="brush: js">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { - return accumulator + currentValue; -}, 0); -// sum is 6 - -</pre> - -<p>Alternatively written with an arrow function:</p> - -<pre class="brush: js">var total = [ 0, 1, 2, 3 ].reduce( - ( accumulator, currentValue ) => accumulator + currentValue, - 0 -);</pre> - -<h3 id="Sum_of_values_in_an_object_array">Sum of values in an object array</h3> - -<p>To sum up the values contained in an array of objects, you <strong>must</strong> supply an <code>initialValue</code>, so that each item passes through your function.</p> - -<pre class="brush: js">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 -</pre> - -<p>Alternatively written with an arrow function:</p> - -<pre class="brush: js">var initialValue = 0; -var sum = [{x: 1}, {x: 2}, {x: 3}].reduce( - (accumulator, currentValue) => accumulator + currentValue.x - ,initialValue -); - -console.log(sum) // logs 6</pre> - -<h3 id="Flatten_an_array_of_arrays">Flatten an array of arrays</h3> - -<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( - function(accumulator, currentValue) { - return accumulator.concat(currentValue); - }, - [] -); -// flattened is [0, 1, 2, 3, 4, 5] -</pre> - -<p>Alternatively written with an arrow function:</p> - -<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( - ( accumulator, currentValue ) => accumulator.concat(currentValue), - [] -); -</pre> - -<h3 id="Counting_instances_of_values_in_an_object">Counting instances of values in an object</h3> - -<pre class="brush: js">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 } -</pre> - -<h3 id="Grouping_objects_by_a_property">Grouping objects by a property</h3> - -<pre class="brush: js">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 }] -// } -</pre> - -<h3 id="Bonding_arrays_contained_in_an_array_of_objects_using_the_spread_operator_and_initialValue">Bonding arrays contained in an array of objects using the spread operator and initialValue</h3> - -<pre class="brush: js">// 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' -// ]</pre> - -<h3 id="Remove_duplicate_items_in_array">Remove duplicate items in array</h3> - -<div class="blockIndicator note"> -<p><strong>Note:</strong> If you are using an environment compatible with {{jsxref("Set")}} and {{jsxref("Array.from()")}}, you could use <code>let orderedArray = Array.from(new Set(myArray));</code> to get an array where duplicate items have been removed.</p> -</div> - -<pre class="brush: js">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);</pre> - -<h3 id="Running_Promises_in_Sequence">Running Promises in Sequence</h3> - -<pre class="brush: js">/** - * 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 -</pre> - -<h3 id="Function_composition_enabling_piping">Function composition enabling piping</h3> - -<pre class="brush: js">// 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 - -</pre> - -<h3 id="write_map_using_reduce">write map using reduce</h3> - -<pre class="brush: js">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] - -</pre> - -<h2 id="Polyfill">Polyfill</h2> - -<pre class="brush: js">// 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; - } - }); -} -</pre> - -<p>If you need to support truly obsolete JavaScript engines that do not support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a></code>, it is best not to polyfill <code>Array.prototype</code> methods at all, as you cannot make them <strong>non-enumerable</strong>.</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.8.</td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ES6')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Array.reduce")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Array.prototype.reduceRight()")}}</li> -</ul> 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 ---- -<div>{{JSRef}}</div> - -<p>The <strong><code>Function</code> constructor</strong> creates a new <code>Function</code> 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.</p> - -<div>{{EmbedInteractiveExample("pages/js/function-constructor.html")}}</div> - - - -<p>Every JavaScript function is actually a <code>Function</code> object. This can be seen with the code <code>(function(){}).constructor === Function</code> which returns true.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> - <dd>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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> - <dt><code>functionBody</code></dt> - <dd>A string containing the JavaScript statements comprising the function definition.</dd> -</dl> - -<h2 id="Description">Description</h2> - -<p><code>Function</code> objects created with the <code>Function</code> constructor are parsed when the function is created. This is less efficient than declaring a function with a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> or <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> and calling it within your code because such functions are parsed with the rest of the code.</p> - -<p>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 <code>undefined</code>.</p> - -<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> - -<h2 id="Properties_and_Methods_of_Function">Properties and Methods of <code>Function</code></h2> - -<p>The global <code>Function</code> 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")}}.</p> - -<h2 id="Function_prototype_object"><code>Function</code> prototype object</h2> - -<h3 id="Properties">Properties</h3> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}</div> - -<h3 id="Methods">Methods</h3> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}</div> - -<h2 id="Function_instances"><code>Function</code> instances</h2> - -<p><code>Function</code> 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 <code>Function</code> instances.</p> - -<h2 id="Examples">Examples</h2> - -<h3 id="Specifying_arguments_with_the_Function_constructor">Specifying arguments with the <code>Function</code> constructor</h3> - -<p>The following code creates a <code>Function</code> object that takes two arguments.</p> - -<pre class="brush: js">// 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 -</pre> - -<p>The arguments "<code>a</code>" and "<code>b</code>" are formal argument names that are used in the function body, "<code>return a + b</code>".</p> - -<h3 id="Difference_between_Function_constructor_and_function_declaration">Difference between Function constructor and function declaration</h3> - -<p>Functions created with the <code>Function</code> 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 <code>Function</code> constructor was created. This is different from using {{jsxref("eval")}} with code for a function expression.</p> - -<pre class="brush: js">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<code> -</code></pre> - -<p>While this code works in web browsers, <code>f1()</code> will produce a <code>ReferenceError</code> in Node.js, as <code>x</code> will not be found. This is because the top-level scope in Node is not the global scope, and <code>x</code> will be local to the module.</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition. Implemented in JavaScript 1.0.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.3', 'Function')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-function-objects', 'Function')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div> - - -<p>{{Compat("javascript.builtins.Function")}}</p> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{jsxref("Functions", "Functions and function scope")}}</li> - <li>{{jsxref("Statements/function", "function statement")}}</li> - <li>{{jsxref("Operators/function", "function expression")}}</li> - <li>{{jsxref("Statements/function*", "function* statement")}}</li> - <li>{{jsxref("Operators/function*", "function* expression")}}</li> - <li>{{jsxref("AsyncFunction")}}</li> - <li>{{jsxref("GeneratorFunction")}}</li> -</ul> 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 ---- -<div> - <div> - {{jsSidebar("Objects")}}</div> -</div> -<h2 id="Summary" name="Summary">Summary</h2> -<p>This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.</p> -<div class="onlyinclude"> - <p>The term "global objects" (or standard built-in objects) here is not to be confused with the <em>global object</em>. Here, global objects refer to <em>objects in the global scope</em> (but only if ECMAScript 5 strict mode is not used! Otherwise it returns <code>undefined</code>). The <em>global object</em> itself can be accessed by the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope <em>consists</em><em> of</em> the properties of the global object (including inherited properties, if any).</p> - <p>Other objects in the global scope are either <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">created by the user script</a> or provided by the host application. The host objects available in browser contexts are documented in the <a href="/en-US/docs/Web/API/Reference">API reference</a>. For more information about the distinction between the <a href="/en-US/docs/DOM/DOM_Reference">DOM</a> and core <a href="/en-US/docs/Web/JavaScript">JavaScript</a>, see <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> - <h2 id="Standard_objects_(by_category)">Standard objects (by category)</h2> - <h3 id="Value_properties">Value properties</h3> - <p>Global properties returning a simple value.</p> - <ul> - <li>{{jsxref("Infinity")}}</li> - <li>{{jsxref("NaN")}}</li> - <li>{{jsxref("undefined")}}</li> - <li>{{jsxref("null")}} literal</li> - </ul> - <h3 id="Function_properties">Function properties</h3> - <p>Global functions returning the result of a specific routine.</p> - <ul> - <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> - <li>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline()}}</li> - <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> - <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> - <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> - <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> - <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> - <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> - <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> - <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> - <li>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline()}}</li> - <li>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline()}}</li> - </ul> - <h3 id="Fundamental_objects">Fundamental objects</h3> - <p>General language objects, functions and errors.</p> - <ul> - <li>{{jsxref("Object")}}</li> - <li>{{jsxref("Function")}}</li> - <li>{{jsxref("Boolean")}}</li> - <li>{{jsxref("Symbol")}} {{experimental_inline()}}</li> - <li>{{jsxref("Error")}}</li> - <li>{{jsxref("EvalError")}}</li> - <li>{{jsxref("InternalError")}}</li> - <li>{{jsxref("RangeError")}}</li> - <li>{{jsxref("ReferenceError")}}</li> - <li>{{jsxref("StopIteration")}}</li> - <li>{{jsxref("SyntaxError")}}</li> - <li>{{jsxref("TypeError")}}</li> - <li>{{jsxref("URIError")}}</li> - </ul> - <h3 id="Numbers_and_dates">Numbers and dates</h3> - <p>Objects dealing with numbers, dates and mathematical calculations.</p> - <ul> - <li>{{jsxref("Number")}}</li> - <li>{{jsxref("Math")}}</li> - <li>{{jsxref("Date")}}</li> - </ul> - <h3 id="Text_processing">Text processing</h3> - <p>Objects for manipulating texts.</p> - <ul> - <li>{{jsxref("String")}}</li> - <li>{{jsxref("RegExp")}}</li> - </ul> - <h3 id="Indexed_collections">Indexed collections</h3> - <p>Collections ordered by an index. Array-type objects.</p> - <ul> - <li>{{jsxref("Array")}}</li> - <li>{{jsxref("Int8Array")}}</li> - <li>{{jsxref("Uint8Array")}}</li> - <li>{{jsxref("Uint8ClampedArray")}}</li> - <li>{{jsxref("Int16Array")}}</li> - <li>{{jsxref("Uint16Array")}}</li> - <li>{{jsxref("Int32Array")}}</li> - <li>{{jsxref("Uint32Array")}}</li> - <li>{{jsxref("Float32Array")}}</li> - <li>{{jsxref("Float64Array")}}</li> - <li>{{jsxref("ParallelArray")}} {{non-standard_inline()}}</li> - </ul> - <h3 id="Keyed_collections">Keyed collections</h3> - <p>Collections of objects as keys. Elements iterable in insertion order.</p> - <ul> - <li>{{jsxref("Map")}} {{experimental_inline()}}</li> - <li>{{jsxref("Set")}} {{experimental_inline()}}</li> - <li>{{jsxref("WeakMap")}} {{experimental_inline()}}</li> - <li>{{jsxref("WeakSet")}} {{experimental_inline()}}</li> - </ul> - <h3 id="Structured_data">Structured data</h3> - <p>Data buffers and <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation.</p> - <ul> - <li>{{jsxref("ArrayBuffer")}}</li> - <li>{{jsxref("DataView")}}</li> - <li>{{jsxref("JSON")}}</li> - </ul> - <h3 id="Control_abstraction_objects">Control abstraction objects</h3> - <ul> - <li>{{jsxref("Iterator")}} {{non-standard_inline()}}</li> - <li>{{jsxref("Generator")}} {{experimental_inline()}}</li> - <li>{{jsxref("Promise")}} {{experimental_inline()}}</li> - </ul> - <h3 id="Reflection">Reflection</h3> - <ul> - <li>{{jsxref("Reflect")}} {{experimental_inline()}}</li> - <li>{{jsxref("Proxy")}} {{experimental_inline()}}</li> - </ul> - <h3 id="Internationalization">Internationalization</h3> - <p>Additions to the ECMAScript core for language-sensitive functionalities.</p> - <ul> - <li>{{jsxref("Intl")}}</li> - <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> - <li>{{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> - <li>{{jsxref("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> - </ul> - <h3 id="Other">Other</h3> - <ul> - <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code></li> - </ul> -</div> -<p> </p> 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 ---- -<div> </div> - -<p dir="rtl">مقدار null نمایان گر مقداری هست که به صورت دستی (عمدی) می توانیم به یک متغییر نسبت دهیم،null یکی از {{Glossary("Primitive", "نوع های اولیه")}}. جاوا اسکریپت می باشد.</p> - -<h2 dir="rtl" id="شیوه_ی_نوشتن">شیوه ی نوشتن</h2> - -<pre dir="rtl"><code>null</code></pre> - -<h2 dir="rtl" id="توضیح">توضیح</h2> - -<p dir="rtl" id="Syntax">null باید به صورت حروف کوچک نوشته شود،null اقلب برای مشخص کردن مکان object به کار برده می شود و به هیچ object وابسته نمی باشد</p> - -<p dir="rtl">زمانی که می خواهید مقدار null یا undefined را بررسی کنید به <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">تفاوت مابین عملگر های بررسی (==) و (===) اگاه باشید</a>.</p> - -<pre class="brush: js">// 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" -</pre> - -<h3 dir="rtl" id="تفاوت_بین_null_و_undefined">تفاوت بین null و undefined</h3> - -<pre class="brush: js">typeof null // object (bug in ECMAScript, should be null) -typeof undefined // undefined -null === undefined // false -null == undefined // true -</pre> - -<h2 dir="rtl" id="مشخصات">مشخصات</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">مشخصات</th> - <th scope="col">وضعیت</th> - <th scope="col">توضیحات</th> - </tr> - <tr> - <td>{{SpecName('ES1')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-4.3.11', 'null value')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-null-value', 'null value')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-null-value', 'null value')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 dir="rtl" id="سازگاری_مرورگرها">سازگاری مرورگرها</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 dir="rtl" id="بیشتر_بخوانید">بیشتر بخوانید</h2> - -<ul> - <li>{{jsxref("undefined")}}</li> - <li>{{jsxref("NaN")}}</li> -</ul> 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 ---- -<div>{{JSRef("Global_Objects", "RegExp")}}</div> - -<h2 id="Summary">Summary</h2> - -<p>The <code><strong>RegExp</strong></code> constructor creates a regular expression object for matching text with a pattern.</p> - -<p>For an introduction on what regular expressions are, read the <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions chapter in the JavaScript Guide</a>.</p> - -<h2 id="Constructor">Constructor</h2> - -<p>Literal and constructor notations are possible:</p> - -<pre class="syntaxbox"><code>/<em>pattern</em>/<em>flags; -</em></code> -new <code>RegExp(<em>pattern</em> <em>[, flags]</em>)</code>; -</pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>pattern</code></dt> - <dd>The text of the regular expression.</dd> - <dt><code>flags</code></dt> - <dd> - <p>If specified, flags can have any combination of the following values:</p> - - <dl> - <dt><code>g</code></dt> - <dd>global match</dd> - <dt><code>i</code></dt> - <dd>ignore case</dd> - <dt><code>m</code></dt> - <dd>multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of <em>each</em> line (delimited by \n or \r), not only the very beginning or end of the whole input string)</dd> - <dt><code>y</code></dt> - <dd>sticky; matches only from the index indicated by the <code>lastIndex</code> property of this regular expression in the target string (and does not attempt to match from any later indexes).</dd> - </dl> - </dd> -</dl> - -<h2 id="Description">Description</h2> - -<p>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:</p> - -<pre class="brush: js">/ab+c/i; -new RegExp("ab+c", "i"); -</pre> - -<p>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.</p> - -<p>The constructor of the regular expression object, for example, <code>new RegExp("ab+c")</code>, 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.</p> - -<p>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:</p> - -<pre class="brush: js">var re = /\w+/; -var re = new RegExp("\\w+"); -</pre> - -<h2 id="Special_characters_meaning_in_regular_expressions">Special characters meaning in regular expressions</h2> - -<ul> - <li><a href="#character-classes">Character Classes</a></li> - <li><a href="#character-sets">Character Sets</a></li> - <li><a href="#boundaries">Boundaries</a></li> - <li><a href="#grouping-back-references">Grouping and back references</a></li> - <li><a href="#quantifiers">Quantifiers</a></li> -</ul> - -<table class="fullwidth-table"> - <tbody> - <tr id="character-classes"> - <th colspan="2">Character Classes</th> - </tr> - <tr> - <th>Character</th> - <th>Meaning</th> - </tr> - <tr> - <td><code>.</code></td> - <td> - <p>(The dot, the decimal point) matches any single character <em>except</em> the newline characters: <code>\n</code> <code>\r</code> <code>\u2028</code> or <code>\u2029</code>.</p> - - <p>Note that the <code>m</code> multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines the character set <code>[^]</code> can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.</p> - - <p>For example, <code>/.y/</code> matches "my" and "ay", but not "yes", in "yes make my day".</p> - </td> - </tr> - <tr> - <td><code>\d</code></td> - <td> - <p>Matches a digit character in the basic Latin alphabet. Equivalent to <code>[0-9]</code>.</p> - - <p>For example, <code>/\d/</code> or <code>/[0-9]/</code> matches '2' in "B2 is the suite number."</p> - </td> - </tr> - <tr> - <td><code>\D</code></td> - <td> - <p>Matches any character that is not a digit in the basic Latin alphabet. Equivalent to <code>[^0-9]</code>.</p> - - <p>For example, <code>/\D/</code> or <code>/[^0-9]/</code> matches 'B' in "B2 is the suite number."</p> - </td> - </tr> - <tr> - <td><code>\w</code></td> - <td> - <p>Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to <code>[A-Za-z0-9_]</code>.</p> - - <p>For example, <code>/\w/</code> matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."</p> - </td> - </tr> - <tr> - <td><code>\W</code></td> - <td> - <p>Matches any character that is not a word character from the basic Latin alphabet. Equivalent to <code>[^A-Za-z0-9_]</code>.</p> - - <p>For example, <code>/\W/</code> or <code>/[^A-Za-z0-9_]/</code> matches '%' in "50%."</p> - </td> - </tr> - <tr> - <td><code>\s</code></td> - <td> - <p>Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to <code>[ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004 \u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f \u3000]</code>.</p> - - <p>For example, <code>/\s\w*/</code> matches ' bar' in "foo bar."</p> - </td> - </tr> - <tr> - <td><code>\S</code></td> - <td> - <p>Matches a single character other than white space. Equivalent to <code><code>[^ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004 \u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]</code></code>.</p> - - <p>For example, <code>/\S\w*/</code> matches 'foo' in "foo bar."</p> - </td> - </tr> - <tr> - <td><code>\t</code></td> - <td>Matches a tab.</td> - </tr> - <tr> - <td><code>\r</code></td> - <td>Matches a carriage return.</td> - </tr> - <tr> - <td><code>\n</code></td> - <td>Matches a linefeed.</td> - </tr> - <tr> - <td><code>\v</code></td> - <td>Matches a vertical tab.</td> - </tr> - <tr> - <td><code>\f</code></td> - <td>Matches a form-feed.</td> - </tr> - <tr> - <td><code>[\b]</code></td> - <td>Matches a backspace. (Not to be confused with <code>\b</code>)</td> - </tr> - <tr> - <td><code>\0</code></td> - <td>Matches a NUL character. Do not follow this with another digit.</td> - </tr> - <tr> - <td><code>\c<em>X</em></code></td> - <td> - <p>Where <code><em>X</em></code> is a letter from A - Z. Matches a control character in a string.</p> - - <p>For example, <code>/\cM/</code> matches control-M in a string.</p> - </td> - </tr> - <tr> - <td><code>\x<em>hh</em></code></td> - <td>Matches the character with the code <code><em>hh</em></code> (two hexadecimal digits)</td> - </tr> - <tr> - <td><code>\u<em>hhhh</em></code></td> - <td>Matches the character with the Unicode value <code><em>hhhh</em></code> (four hexadecimal digits).</td> - </tr> - <tr> - <td><code>\</code></td> - <td> - <p>For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.</p> - - <p>For example, <code>/b/</code> matches the character 'b'. By placing a backslash in front of b, that is by using <code>/\b/</code>, the character becomes special to mean match a word boundary.</p> - - <p><em>or</em></p> - - <p>For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.</p> - - <p>For example, * is a special character that means 0 or more occurrences of the preceding character should be matched; for example, <code>/a*/</code> means match 0 or more "a"s. To match <code>*</code> literally, precede it with a backslash; for example, <code>/a\*/</code> matches 'a*'.</p> - </td> - </tr> - </tbody> - <tbody> - <tr id="character-sets"> - <th colspan="2"> - <p>Character Sets</p> - </th> - </tr> - <tr> - <th>Character</th> - <th>Meaning</th> - </tr> - <tr> - <td><code>[xyz]</code></td> - <td> - <p>A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen.</p> - - <p>For example, <code>[abcd]</code> is the same as <code>[a-d]</code>. They match the 'b' in "brisket" and the 'c' in "chop".</p> - </td> - </tr> - <tr> - <td><code>[^xyz]</code></td> - <td> - <p>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.</p> - - <p>For example, <code>[^abc]</code> is the same as <code>[^a-c]</code>. They initially match 'o' in "bacon" and 'h' in "chop."</p> - </td> - </tr> - </tbody> - <tbody> - <tr id="boundaries"> - <th colspan="2">Boundaries</th> - </tr> - <tr> - <th>Character</th> - <th>Meaning</th> - </tr> - <tr> - <td><code>^</code></td> - <td> - <p>Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.</p> - - <p>For example, <code>/^A/</code> does not match the 'A' in "an A", but does match the first 'A' in "An A."</p> - </td> - </tr> - <tr> - <td><code>$</code></td> - <td> - <p>Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.</p> - - <p>For example, <code>/t$/</code> does not match the 't' in "eater", but does match it in "eat".</p> - </td> - </tr> - <tr> - <td><code>\b</code></td> - <td> - <p>Matches a zero-width word boundary, such as between a letter and a space. (Not to be confused with <code>[\b]</code>)</p> - - <p>For example, <code>/\bno/</code> matches the 'no' in "at noon"; <code>/ly\b/</code> matches the 'ly' in "possibly yesterday."</p> - </td> - </tr> - <tr> - <td><code>\B</code></td> - <td> - <p>Matches a zero-width non-word boundary, such as between two letters or between two spaces.</p> - - <p>For example, <code>/\Bon/</code> matches 'on' in "at noon", and <code>/ye\B/</code> matches 'ye' in "possibly yesterday."</p> - </td> - </tr> - </tbody> - <tbody> - <tr id="grouping-back-references"> - <th colspan="2">Grouping and back references</th> - </tr> - <tr> - <th>Character</th> - <th>Meaning</th> - </tr> - <tr> - <td><code>(<em>x</em>)</code></td> - <td> - <p>Matches <code><em>x</em></code> and remembers the match. These are called capturing parentheses.</p> - - <p>For example, <code>/(foo)/</code> matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements <code>[1], ..., [n]</code> or from the predefined <code>RegExp</code> object's properties <code>$1, ..., $9</code>.</p> - - <p>Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).</p> - </td> - </tr> - <tr> - <td><code>\<em>n</em></code></td> - <td> - <p>Where <code><em>n</em></code> is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).</p> - - <p>For example, <code>/apple(,)\sorange\1/</code> matches 'apple, orange,' in "apple, orange, cherry, peach." A more complete example follows this table.</p> - </td> - </tr> - <tr> - <td><code>(?:<em>x</em>)</code></td> - <td>Matches <code><em>x</em></code> 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 <code>[1], ..., [n]</code> or from the predefined <code>RegExp</code> object's properties <code>$1, ..., $9</code>.</td> - </tr> - </tbody> - <tbody> - <tr id="quantifiers"> - <th colspan="2">Quantifiers</th> - </tr> - <tr> - <th>Character</th> - <th>Meaning</th> - </tr> - <tr> - <td><code><em>x</em>*</code></td> - <td> - <p>Matches the preceding item <em>x</em> 0 or more times.</p> - - <p>For example, <code>/bo*/</code> matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled", but nothing in "A goat grunted".</p> - </td> - </tr> - <tr> - <td><code><em>x</em>+</code></td> - <td> - <p>Matches the preceding item <em>x</em> 1 or more times. Equivalent to <code>{1,}</code>.</p> - - <p>For example, <code>/a+/</code> matches the 'a' in "candy" and all the a's in "caaaaaaandy".</p> - </td> - </tr> - <tr> - <td><code><em>x</em>*?</code><br> - <code><em>x</em>+?</code></td> - <td> - <p>Matches the preceding item <em>x</em> like <code>*</code> and <code>+</code> from above, however the match is the smallest possible match.</p> - - <p>For example, <code>/".*?"/</code> matches '"foo"' in '"foo" "bar"' and does not match '"foo" "bar"' as without the <code>?</code> behind the <code>*</code>.</p> - </td> - </tr> - <tr> - <td><code><em>x</em>?</code></td> - <td> - <p>Matches the preceding item <em>x</em> 0 or 1 time.</p> - - <p>For example, <code>/e?le?/</code> matches the 'el' in "angel" and the 'le' in "angle."</p> - - <p>If used immediately after any of the quantifiers <code>*</code>, <code>+</code>, <code>?</code>, or <code>{}</code>, 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).</p> - - <p>Also used in lookahead assertions, described under <code>(?=)</code>, <code>(?!)</code>, and <code>(?:)</code> in this table.</p> - </td> - </tr> - <tr> - <td><code><em>x</em>(?=<em>y</em>)</code></td> - <td>Matches <code><em>x</em></code> only if <code><em>x</em></code> is followed by <code><em>y</em></code>. For example, <code>/Jack(?=Sprat)/</code> matches 'Jack' only if it is followed by 'Sprat'. <code>/Jack(?=Sprat|Frost)/</code> matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.</td> - </tr> - <tr> - <td><code><em>x</em>(?!<em>y</em>)</code></td> - <td> - <p>Matches <code><em>x</em></code> only if <code><em>x</em></code> is not followed by <code><em>y</em></code>. For example, <code>/\d+(?!\.)/</code> matches a number only if it is not followed by a decimal point.</p> - - <p><code>/\d+(?!\.)/.exec("3.141")</code> matches 141 but not 3.141.</p> - </td> - </tr> - <tr> - <td><code><em>x</em>|<em>y</em></code></td> - <td> - <p>Matches either <code><em>x</em></code> or <code><em>y</em></code>.</p> - - <p>For example, <code>/green|red/</code> matches 'green' in "green apple" and 'red' in "red apple."</p> - </td> - </tr> - <tr> - <td><code><em>x</em>{<em>n</em>}</code></td> - <td> - <p>Where <code><em>n</em></code> is a positive integer. Matches exactly <code><em>n</em></code> occurrences of the preceding item <em>x</em>.</p> - - <p>For example, <code>/a{2}/</code> 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."</p> - </td> - </tr> - <tr> - <td><code><em>x</em>{<em>n</em>,}</code></td> - <td> - <p>Where <code><em>n</em></code> is a positive integer. Matches at least <code><em>n</em></code> occurrences of the preceding item <em>x</em>.</p> - - <p>For example, <code>/a{2,}/</code> doesn't match the 'a' in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy."</p> - </td> - </tr> - <tr> - <td><code><em>x</em>{<em>n</em>,<em>m</em>}</code></td> - <td> - <p>Where <code><em>n</em></code> and <code><em>m</em></code> are positive integers. Matches at least <code><em>n</em></code> and at most <code><em>m</em></code> occurrences of the preceding item <em>x</em>.</p> - - <p>For example, <code>/a{1,3}/</code> 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.</p> - </td> - </tr> - </tbody> -</table> - -<h3 id="Properties"><span style="font-size: 1.714285714285714rem;">Properties</span></h3> - -<dl> - <dt>{{jsxref("RegExp.prototype")}}</dt> - <dd>Allows the addition of properties to all objects.</dd> - <dt>RegExp.length</dt> - <dd>The value of <code>RegExp.length</code> is 2.</dd> -</dl> - -<div>{{jsOverrides("Function", "Properties", "prototype")}}</div> - -<h3 id="Methods">Methods</h3> - -<p>The global <code>RegExp</code> object has no methods of its own, however, it does inherit some methods through the prototype chain.</p> - -<div>{{jsOverrides("Function", "Methods", "prototype")}}</div> - -<h2 id="RegExp_prototype_objects_and_instances"><code>RegExp</code> prototype objects and instances</h2> - -<h3 id="Properties_2">Properties</h3> - -<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype','Properties')}}</div> - -<h3 id="Methods_2">Methods</h3> - -<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype','Methods')}}</div> - -<h2 id="Examples">Examples</h2> - -<h3 id="Example_Using_a_regular_expression_to_change_data_format">Example: Using a regular expression to change data format</h3> - -<p>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 <em>first last</em> and output it in the format <em>last</em>, <em>first</em>. In the replacement text, the script uses <code>$1</code> and <code>$2</code> to indicate the results of the corresponding matching parentheses in the regular expression pattern.</p> - -<pre class="brush: js">var re = /(\w+)\s(\w+)/; -var str = "John Smith"; -var newstr = str.replace(re, "$2, $1"); -console.log(newstr);</pre> - -<p>This displays "Smith, John".</p> - -<h3 id="Example_Using_regular_expression_on_multiple_lines">Example: Using regular expression on multiple lines</h3> - -<pre class="brush: js">var s = "Please yes\nmake my day!"; -s.match(/yes.*day/); -// Returns null -s.match(/yes[^]*day/); -// Returns 'yes\nmake my day' -</pre> - -<h3 id="Example_Using_a_regular_expression_with_the_sticky_flag">Example: Using a regular expression with the "sticky" flag</h3> - -<p>This example demonstrates how one could use the sticky flag on regular expressions to match individual lines of multiline input.</p> - -<pre class="brush: js">var text = "First line\nSecond line"; -var regex = /(\S+) line\n?/y; - -var match = regex.exec(text); -<span style="font-size: 1rem;">console.log</span>(match[1]); // prints "First" -<span style="font-size: 1rem;">console.log</span>(regex.lastIndex); // prints 11 - -var match2 = regex.exec(text); -<span style="font-size: 1rem;">console.log</span>(match2[1]); // prints "Second" -<span style="font-size: 1rem;">console.log</span>(regex.lastIndex); // prints "22" - -var match3 = regex.exec(text); -<span style="font-size: 1rem;">console.log</span>(match3 === null); // prints "true"</pre> - -<p>One can test at run-time whether the sticky flag is supported, using <code>try { … } catch { … }</code>. For this, either an <code>eval(…)</code> expression or the <code>RegExp(<var>regex-string</var>, <var>flags-string</var>)</code> syntax must be used (since the <code>/<var>regex</var>/<var>flags</var></code> notation is processed at compile-time, so throws an exception before the <code>catch</code> block is encountered). For example:</p> - -<pre class="brush: js">var supports_sticky; -try { RegExp('','y'); supports_sticky = true; } -catch(e) { supports_sticky = false; } -alert(supports_sticky); // alerts "true"</pre> - -<h3 id="Example_Regular_expression_and_Unicode_characters">Example: Regular expression and Unicode characters</h3> - -<p>As mentioned above, <code>\w</code> or <code>\W</code> 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 <code>\uhhhh</code>., where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.</p> - -<pre class="brush: js">var text = "Образец text на русском языке"; -var regex = /[\u0400-\u04FF]+/g; - -var match = regex.exec(text); -<span style="font-size: 1rem;">console.log</span>(match[0]); // prints "Образец" -<span style="font-size: 1rem;">console.log</span>(regex.lastIndex); // prints "7" - -var match2 = regex.exec(text); -<span style="font-size: 1rem;">console.log</span>(match2[0]); // prints "на" [did not print "text"] -<span style="font-size: 1rem;">console.log</span>(regex.lastIndex); // prints "15" - -// and so on</pre> - -<p>Here's an external resource for getting the complete Unicode block range for different scripts: <a href="http://kourge.net/projects/regexp-unicode-block" title="http://kourge.net/projects/regexp-unicode-block">Regexp-unicode-block</a></p> - -<h3 id="Example_Extracting_subdomain_name_from_URL">Example: Extracting subdomain name from URL</h3> - -<pre class="brush: js">var url = "http://xxx.domain.com"; -<span style="font-size: 1rem;">console.log</span>(/[^.]+/.exec(url)[0].substr(7)); // prints "xxx"</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>ECMAScript 1st Edition. Implemented in JavaScript 1.1</td> - <td>Standard</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - <tr> - <td>Sticky flag ("y")</td> - <td>39 (behind flag)</td> - <td>{{ CompatGeckoDesktop("1.9") }} ES4-Style {{bug(773687)}}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - <tr> - <td>Sticky flag ("y")</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatGeckoDesktop("1.9") }} ES4-Style {{bug(773687)}}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - <td>{{ CompatNo() }}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" title="JavaScript/Guide/Regular_Expressions">Regular Expressions</a> chapter in the <a href="/en-US/docs/Web/JavaScript/Guide" title="JavaScript/Guide">JavaScript Guide</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match">String.prototype.match()</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">String.prototype.replace()</a></li> -</ul> 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 ---- -<div dir="rtl"> - {{JSRef("Global_Objects", "RegExp")}}</div> -<h2 dir="rtl" id="Summary" name="Summary">خلاصه</h2> -<p dir="rtl"><strong>متد test یک جستجو برای یافتن رشته خاص در متن یا رشته مورد نظر انجام میدهد و True یا False برمیگرداند.</strong></p> -<h2 dir="rtl" id="Syntax" name="Syntax">ساختار</h2> -<pre dir="rtl"><var>regexObj</var>.test(str)</pre> -<h3 dir="rtl" id="Parameters" name="Parameters"><strong>پارامتر ها</strong></h3> -<dl> - <dt dir="rtl"> - <code>str</code></dt> - <dd dir="rtl"> - <strong>رشته ای که میخواهید با متن مورد نظر تطابق دهید.</strong></dd> -</dl> -<h3 dir="rtl" id="مقدار_بازگشتی"><strong>مقدار بازگشتی</strong></h3> -<p dir="rtl"><strong>مقدار بازگشتی از نوع Boolean بوده و True یا False میباشد.</strong></p> -<h2 dir="rtl" id="Description" name="Description">توضیحات</h2> -<p dir="rtl"><strong>متد test() زمانی استفاده میشود که میخواهید الگو مورد نظر خود را در یک متن جستجو کنید و از وجود آن در متن مورد نظر با خبر شوید.</strong></p> -<p dir="rtl"><strong>متدهای مرتبط :</strong> {jsxref("String.search") , {jsxref("RegExp.exec", "exec")</p> -<h2 dir="rtl" id="Examples" name="Examples">مثال</h2> -<h3 dir="rtl" id="Example:_Using_test" name="Example:_Using_test"><code>مثال: استفاده از test</code></h3> -<p dir="rtl"><strong>مثال زیر یک خروجی را چاپ میکند که اشاره به موفقیت آمیز بودن جستجو دارد:</strong></p> -<pre class="brush: js" dir="rtl">function testinput(re, str){ - var midstring; - if (re.test(str)) { - midstring = " contains "; - } else { - midstring = " does not contain "; - } - console.log(str + midstring + re.source); -} -</pre> -<h2 dir="rtl" id="خصوصیات">خصوصیات</h2> -<table class="standard-table" dir="rtl"> - <tbody> - <tr> - <th scope="col">خصوصیت</th> - <th scope="col">وضعیت</th> - <th scope="col">یاداشت</th> - </tr> - <tr> - <td>ECMAScript 3rd Edition. Implemented in JavaScript 1.2</td> - <td>Standard</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-15.10.6.3', 'RegExp.test')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-regexp.prototype.test', 'RegExp.test')}}</td> - <td>{{Spec2('ES6')}}</td> - <td> </td> - </tr> - </tbody> -</table> -<h2 dir="rtl" id="سازگاری_با_مرورگرها">سازگاری با مرورگرها</h2> -<p dir="rtl">{{ CompatibilityTable() }}</p> -<div dir="rtl" id="compat-desktop"> - <table class="compat-table"> - <tbody> - <tr> - <th>خصوصیات</th> - <th>گوگل کروم</th> - <th>فایرفاکس</th> - <th>اینترنت اکسپلورر</th> - <th>اپرا</th> - <th>سافاری</th> - </tr> - <tr> - <td>پشتیبانی ابتدایی</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> - </table> -</div> -<div dir="rtl" id="compat-mobile"> - <table class="compat-table"> - <tbody> - <tr> - <th>خصوصیات</th> - <th>اندروید</th> - <th>گوگل کروم برای اندروید</th> - <th>فایرفاکس موبایل</th> - <th>اینترنت اکسپلورر موبایل</th> - <th>اپرا موبایل</th> - <th>سافاری موبایل</th> - </tr> - <tr> - <td>پشتیبانی ابتدایی</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatVersionUnknown() }}</td> - </tr> - </tbody> - </table> -</div> -<h3 dir="rtl" id="sect1"> </h3> -<h3 dir="rtl" id="یادداشتی_برای_Gecko-specific"><strong>یادداشتی برای Gecko-specific</strong></h3> -<p dir="rtl"><strong>قبل از نسخه Gecko 8.0 {{ geckoRelease("8.0") }} تابع test() مشکلاتی به همراه داشت ، زمانی که این تابع بدون پارامتر ورودی فراخوانی میشد الگو را با متن قبلی مطابقت میداد (RegExp.input property) در حالی که بایستی رشته "undefined" را قرار میداد. در حال حاضر این مشکل برطرف شده است و <code>این تابع به درستی کار میکند.</code></strong></p> -<p dir="rtl"> </p> -<p dir="rtl"> </p> -<h2 dir="rtl" id="همچنین_سری_بزنید_به">همچنین سری بزنید به :</h2> -<ul dir="rtl"> - <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" title="JavaScript/Guide/Regular_Expressions">Regular Expressions</a> chapter in the <a href="/en-US/docs/Web/JavaScript/Guide" title="JavaScript/Guide">JavaScript Guide</a></li> - <li>{{jsxref("Global_Objects/RegExp", "RegExp")}}</li> -</ul> 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 ---- -<div dir="rtl" style="font-family: sahel,iransans,tahoma,sans-serif;"> -<div>{{JSRef}}</div> - -<div>شیء Set به شما اجازه میدهد مجموعهای از مقادیر منحصر به فرد را از هر نوعی که باشند ذخیره کنید، چه {{Glossary("Primitive", "مقادیر اوّلیّه (Primitive)")}} باشند، چه ارجاعهایی به اشیاء.</div> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">new Set([iterable]);</pre> - -<h3 id="پارامترها">پارامترها</h3> - -<dl> - <dt>iterable</dt> - <dd>اگر یک شیء <a href="/fa-IR/docs/Web/JavaScript/Reference/Statements/for...of">قابل شمارش</a> (iterable) باشد، همهی عناصر آن به مجموعهی جدید ما اضافه میشوند. null نیز در اینجا به منزلهی undefined است.</dd> -</dl> - -<h2 id="توضیح">توضیح</h2> - -<p>هر شیء Set مجموعهای از مقادیر است. این مقادیر به ترتیبی که به مجموعه اضافه شدند شمارش میشوند. یک مقدار در مجموعه فقط میتواند یک بار بیاید (مهمترین تفاوت مجموعه و آرایه در همین است که در مجموعه مقدار تکراری نداریم ولی در آرایه میتوانیم داشته باشیم).</p> - -<h3 id="برابر_بودن_مقدارها">برابر بودن مقدارها</h3> - -<p>از آن جایی که در هر مجموعه باید مقادیر منحصر به فرد داشته باشیم، به صورت خودکار هنگام اضافه شدن عضو جدید به مجموعه برابری مقدارها بررسی میشود. در نسخههای قبلی ECMAScript، الگوریتمی که این بررسی استفاده میکرد با الگوریتم عملگر === فرق داشت. مخصوصا برای مجموعهها عدد صفر مثبت <bdi>+0</bdi> با صفر منفی <bdi>-0</bdi> متفاوت در نظر گرفته میشدند. با این حال در مشخّصاتی که برای ECMAScript 2015 در نظر گرفته شد این مورد تغییر کرد. برای اطّلاعات بیشتر <a href="#Browser compatibility">جدول پشتیبانی مرورگرها</a> از برابری صفر مثبت و منفی را ببینید.</p> - -<p>ضمناً NaN و undefined نیز میتوانند در یک مجموعه ذخیره شوند. در این مورد NaN با NaN برابر در نظر گرفته میشود (در حالی که به صورت عادی NaN !== NaN است).</p> - -<h2 id="خصیصهها">خصیصهها</h2> - -<dl> - <dt><code>Set.length</code></dt> - <dd>مقدار خصیصهی length همیشه 0 است!</dd> - <dt><bdi>{{jsxref("Set.@@species", "get Set[@@species]")}}</bdi></dt> - <dd>تابع سازندهای است که برای اشیاء مشتق شده به کار میرود.</dd> - <dt>{{jsxref("Set.prototype")}}</dt> - <dd>نشاندهندهی prototype تابع سازندهی Set است که اجازه میدهد خصیصههای جدیدی را به تمام اشیائی که از نوع مجموعه هستند اضافه کنید.</dd> -</dl> - -<h2 id="Set_instances"><code>Set</code> instances</h2> - -<p>تمام نمونههای کلاس Set از {{jsxref("Set.prototype")}} ارثبری میکنند.</p> - -<h3 id="خصیصهها_2">خصیصهها</h3> - -<bdi><p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}</p></bdi> - -<h3 id="متُدها">متُدها</h3> - -<bdi><p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}</p></bdi> - -<h2 id="مثالها">مثالها</h2> - -<h3 id="استفاده_از_شیء_Set">استفاده از شیء Set</h3> - -<pre class="brush: js">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 -</pre> - -<h3 id="شمارش_عناصر_مجموعه">شمارش عناصر مجموعه</h3> - -<pre class="brush: js">// 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 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from">Array.from</a> -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</pre> - -<h3 id="پیادهسازی_عملهای_اصلی_در_مجموعهها">پیادهسازی عملهای اصلی در مجموعهها</h3> - -<pre class="brush: js">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] - -</pre> - -<h3 id="ارتباط_مجموعه_و_آرایه">ارتباط مجموعه و آرایه</h3> - -<pre class="brush: js">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</pre> - -<h2 id="مشخّصات">مشخّصات</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-set-objects', 'Set')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="سازگاری_با_مرورگرها"><a id="سازگاری با مرورگرها" name="سازگاری با مرورگرها">سازگاری با مرورگرها</a></h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>ویژگی</th> - <th>Chrome</th> - <th>Edge</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>پشتیبانی ساده</td> - <td> - <p>{{ CompatChrome(38) }} [1]</p> - </td> - <td>12</td> - <td>{{ CompatGeckoDesktop("13") }}</td> - <td>{{ CompatIE("11") }}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td>Constructor argument: <code>new Set(iterable)</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>12</td> - <td>{{ CompatGeckoDesktop("13") }}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>9.0</td> - </tr> - <tr> - <td>iterable</td> - <td>{{ CompatChrome(38) }}</td> - <td>12</td> - <td>{{ CompatGeckoDesktop("17") }}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Set.clear()</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>12</td> - <td>{{CompatGeckoDesktop("19")}}</td> - <td>{{ CompatIE("11") }}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Set.keys(), Set.values(), Set.entries()</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>12</td> - <td>{{CompatGeckoDesktop("24")}}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td><code>Set.forEach()</code></td> - <td>{{ CompatChrome(38) }}</td> - <td>12</td> - <td>{{CompatGeckoDesktop("25")}}</td> - <td>{{ CompatIE("11") }}</td> - <td>25</td> - <td>7.1</td> - </tr> - <tr> - <td>Value equality for -0 and 0</td> - <td>{{ CompatChrome(38) }}</td> - <td>12</td> - <td>{{CompatGeckoDesktop("29")}}</td> - <td>{{CompatNo}}</td> - <td>25</td> - <td>{{CompatSafari(9)}}</td> - </tr> - <tr> - <td>Constructor argument: <code>new Set(null)</code></td> - <td>{{CompatVersionUnknown}}</td> - <td>12</td> - <td>{{CompatGeckoDesktop("37")}}</td> - <td>{{CompatIE(11)}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatSafari(7.1)}}</td> - </tr> - <tr> - <td>Monkey-patched <code>add()</code> in Constructor</td> - <td>{{CompatVersionUnknown}}</td> - <td>12</td> - <td>{{CompatGeckoDesktop("37")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatSafari(9)}}</td> - </tr> - <tr> - <td><code>Set[@@species]</code></td> - <td>{{ CompatChrome(51) }}</td> - <td>13</td> - <td>{{CompatGeckoDesktop("41")}}</td> - <td>{{CompatNo}}</td> - <td>{{ CompatOpera(38) }}</td> - <td>{{CompatSafari(10)}}</td> - </tr> - <tr> - <td><code>Set()</code> without <code>new</code> throws</td> - <td>{{CompatVersionUnknown}}</td> - <td>12</td> - <td>{{CompatGeckoDesktop("42")}}</td> - <td>{{CompatIE(11)}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>9</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(38)}} [1]</td> - <td>{{ CompatGeckoMobile("13") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td>Constructor argument: <code>new Set(iterable)</code></td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(38)}}</td> - <td>{{ CompatGeckoMobile("13") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>9</td> - </tr> - <tr> - <td>iterable</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{ CompatGeckoMobile("17") }}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Set.clear()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("19")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Set.keys(), Set.values(), Set.entries()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("24")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td><code>Set.forEach()</code></td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("25")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>8</td> - </tr> - <tr> - <td>Value equality for -0 and 0</td> - <td>{{CompatNo}}</td> - <td>{{ CompatChrome(38) }}</td> - <td>{{CompatGeckoMobile("29")}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>9</td> - </tr> - <tr> - <td>Constructor argument: <code>new Set(null)</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>8</td> - </tr> - <tr> - <td>Monkey-patched <code>add()</code> in Constructor</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile("37")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>9</td> - </tr> - <tr> - <td><code>Set[@@species]</code></td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("41")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>10</td> - </tr> - <tr> - <td><code>Set()</code> without <code>new</code> throws</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatGeckoMobile("42")}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>9</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] The feature was available behind a preference from Chrome 31. In <code>chrome://flags</code>, activate the entry “Enable Experimental JavaScript”.</p> - -<h2 id="مطالب_مرتبط">مطالب مرتبط</h2> - -<ul> - <li>{{jsxref("Map")}}</li> - <li>{{jsxref("WeakMap")}}</li> - <li>{{jsxref("WeakSet")}}</li> -</ul> -</div> 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 ---- -<div>{{JsSidebar}}</div> - -<p>This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more <a href="/en-US/docs/Web/JavaScript/Reference/About">about this reference</a>.</p> - -<h2 id="Global_Objects">Global Objects</h2> - -<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">JavaScript standard built-in objects</a>, along with their methods and properties.</p> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}</div> - -<h2 id="Statements">Statements</h2> - -<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statements and declarations</a>.</p> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}</div> - -<h2 id="Expressions_and_operators">Expressions and operators</h2> - -<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Operators">JavaScript expressions and operators</a>.</p> - -<div>{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}</div> - -<h2 id="Functions">Functions</h2> - -<p>This chapter documents how to work with <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">JavaScript functions</a> to develop your applications.</p> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments"><code>arguments</code></a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/arrow_functions">Arrow functions</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/default_parameters">Default parameters</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a></li> -</ul> - -<h2 id="Additional_reference_pages">Additional reference pages</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Deprecated features</a></li> -</ul> 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 ---- -<div>{{jsSidebar("Operators")}}</div> - -<div>این بخش از سند شامل تمامی عمل ها و عبارت و کلمات کلیدی بکار رفته در زبان برنامه نویسی جاوااسکریپت می باشد.</div> - -<h2 id="دسته_بندی_عبارت_و_عمل_ها">دسته بندی عبارت و عمل ها</h2> - -<p>لیست زیر براساس الفابت انگلیسی مرتب شده است</p> - -<h3 id="عبارات_اصلی">عبارات اصلی</h3> - -<p>عبارت عمومی و کلمات کلیدی اصلی در جاوا اسکریپت.</p> - -<dl> - <dt>{{jsxref("Operators/this", "this")}}</dt> - <dd dir="rtl">کلمه کلیدی <code>this</code> به محتوایی در درون تابعی که در آن نوشته شده است اشاره می کند.</dd> - <dt>{{jsxref("Operators/function", "function")}}</dt> - <dd dir="rtl">کلمه کلیدی <code>function</code> ٫ تعریف کننده یک تابع است.</dd> - <dt>{{jsxref("Operators/class", "class")}}</dt> - <dd dir="rtl">کلمه کلیدی <code>class</code> ٫ تعریف کننده یک کلاس است.</dd> - <dt>{{jsxref("Operators/function*", "function*")}}</dt> - <dd dir="rtl">کلمه کلیدی <code>function*</code> تعریف کننده یک سازنده کلاس است.</dd> - <dt>{{jsxref("Operators/yield", "yield")}}</dt> - <dd style="direction: rtl;">مکث و از سرگیری می کند تابعی که تولید شده است.</dd> - <dt>{{jsxref("Operators/yield*", "yield*")}}</dt> - <dd dir="rtl">محول می کند به تابع یا آبجکت تولید شده دیگر.</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/async_function", "async function*")}}</dt> - <dd dir="rtl"><code>async function</code> یک تابع async تعریف می کند</dd> - <dt>{{experimental_inline}} {{jsxref("Operators/await", "await")}}</dt> - <dd dir="rtl">مکث و از سرگیری می کند و تابع اسینک (async ) و منتظر اجازه برای تایید را رد می ماند</dd> - <dt>{{jsxref("Global_Objects/Array", "[]")}}</dt> - <dd style="direction: rtl;">تعریف کننده /سازنده یک آرایه .</dd> - <dt>{{jsxref("Operators/Object_initializer", "{}")}}</dt> - <dd dir="rtl">تعریف کننده / سازنده یک آبجکت ( شئی) .</dd> - <dt>{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}</dt> - <dd dir="rtl">یک ترکیب صحیح از عبارتها</dd> - <dt>{{jsxref("Operators/Grouping", "( )")}}</dt> - <dd dir="rtl">دسته بندی عمل ها</dd> -</dl> - -<h3 dir="rtl" id="عبارت_های_سمت_چپ">عبارت های سمت چپ</h3> - -<p dir="rtl">مقدارهای سمت چپ مشخص کردن هدف هستند </p> - -<dl> - <dt>{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> - <dd>عمل های شامل درستی به یک ویژگی یا متد از یک آبجکت(شئی) از قبل تعریف شده<br> - (<code>object.property</code> و <code>object["property"]</code>).</dd> - <dt>{{jsxref("Operators/new", "new")}}</dt> - <dd dir="rtl">عمل <code>new</code> یک سازنده از الگو یا موجودیت از قبل تعریف شده مثل آبجکت </dd> - <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></dt> - <dd>In constructors, <code>new.target</code> refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.</dd> - <dt>{{jsxref("Operators/super", "super")}}</dt> - <dd style="direction: rtl;">کلیدواژه <code>super</code> والد سازنده را صدا می زند</dd> - <dt>{{jsxref("Operators/Spread_operator", "...obj")}}</dt> - <dd>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.</dd> -</dl> - -<h3 id="افزایش_و_کاهش">افزایش و کاهش</h3> - -<p>عملوند پیشوندی/ پسوندی افزایشی و عملوند پیشوندی/پسوندی کاهشی</p> - -<dl> - <dt>{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}</dt> - <dd>عملوند پسوندی افزایشی.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}</dt> - <dd>عملوند پسوندی کاهشی.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}</dt> - <dd>عملوند پیشوندی افزایشی.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</dt> - <dd>عملوند پیشوند کاهشی</dd> -</dl> - -<h3 id="عملوند_های_یکتا">عملوند های یکتا</h3> - -<p>A unary operation is operation with only one operand.</p> - -<dl> - <dt>{{jsxref("Operators/delete", "delete")}}</dt> - <dd dir="rtl">عملوند <code>delete</code> ویژگی /ها را از یک آبجکت حذف می کند.</dd> - <dt>{{jsxref("Operators/void", "void")}}</dt> - <dd dir="rtl">در عمل کننده <code>void</code> مقداری برای بازگشت از یک عبارت وجود ندارد.</dd> - <dt>{{jsxref("Operators/typeof", "typeof")}}</dt> - <dd dir="rtl"><code>typeof</code> نوع آبجکت (شئی )دریافتی را مشخص می کند.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}</dt> - <dd>The unary plus operator converts its operand to Number type.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}</dt> - <dd>The unary negation operator converts its operand to Number type and then negates it.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}</dt> - <dd>Bitwise NOT operator.</dd> - <dt>{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}</dt> - <dd>Logical NOT operator.</dd> -</dl> - -<h3 id="عملوند_های_منطقی">عملوند های منطقی</h3> - -<p>عملوندهای منطقی روی مقدار عددی اعمال می شوند و یک عدد به عنوان نتیجه منطقی عملوند منطقی خواهد بود</p> - -<dl> - <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}</dt> - <dd>عمل جمع.</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}</dt> - <dd>عمل تفریق/منها</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}</dt> - <dd>عمل تقسیم</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}</dt> - <dd>عمل ضرب</dd> - <dt>{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}</dt> - <dd>عمل تقسیم / خروجی باقیماند تقسیم</dd> -</dl> - -<dl> - <dt>{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}</dt> - <dd>عمل توان</dd> -</dl> - -<h3 id="Relational_operators">Relational operators</h3> - -<p>A comparison operator compares its operands and returns a <code>Boolean</code> value based on whether the comparison is true.</p> - -<dl> - <dt>{{jsxref("Operators/in", "in")}}</dt> - <dd>The <code>in</code> operator determines whether an object has a given property.</dd> - <dt>{{jsxref("Operators/instanceof", "instanceof")}}</dt> - <dd>The <code>instanceof</code> operator determines whether an object is an instance of another object.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}</dt> - <dd>Less than operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}</dt> - <dd>Greater than operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}</dt> - <dd>Less than or equal operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</dt> - <dd>Greater than or equal operator.</dd> -</dl> - -<div class="note"> -<p><strong>Note: =></strong> is not an operator, but the notation for <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a>.</p> -</div> - -<h3 id="Equality_operators">Equality operators</h3> - -<p>The result of evaluating an equality operator is always of type <code>Boolean</code> based on whether the comparison is true.</p> - -<dl> - <dt>{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}</dt> - <dd>Equality operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}</dt> - <dd>Inequality operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}</dt> - <dd>Identity operator.</dd> - <dt>{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</dt> - <dd>Nonidentity operator.</dd> -</dl> - -<h3 id="Bitwise_shift_operators">Bitwise shift operators</h3> - -<p>Operations to shift all bits of the operand.</p> - -<dl> - <dt>{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}</dt> - <dd>Bitwise left shift operator.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}</dt> - <dd>Bitwise right shift operator.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</dt> - <dd>Bitwise unsigned right shift operator.</dd> -</dl> - -<h3 id="Binary_bitwise_operators">Binary bitwise operators</h3> - -<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.</p> - -<dl> - <dt>{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}</dt> - <dd>Bitwise AND.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}</dt> - <dd>Bitwise OR.</dd> - <dt>{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</dt> - <dd>Bitwise XOR.</dd> -</dl> - -<h3 id="Binary_logical_operators">Binary logical operators</h3> - -<p>Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.</p> - -<dl> - <dt>{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}</dt> - <dd>Logical AND.</dd> - <dt>{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}</dt> - <dd>Logical OR.</dd> -</dl> - -<h3 id="Conditional_ternary_operator">Conditional (ternary) operator</h3> - -<dl> - <dt>{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> - <dd> - <p>The conditional operator returns one of two values based on the logical value of the condition.</p> - </dd> -</dl> - -<h3 id="Assignment_operators">Assignment operators</h3> - -<p>An assignment operator assigns a value to its left operand based on the value of its right operand.</p> - -<dl> - <dt>{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}</dt> - <dd>Assignment operator.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}</dt> - <dd>Multiplication assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}</dt> - <dd>Division assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}</dt> - <dd>Remainder assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}</dt> - <dd>Addition assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}</dt> - <dd>Subtraction assignment</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}</dt> - <dd>Left shift assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}</dt> - <dd>Right shift assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}</dt> - <dd>Unsigned right shift assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}</dt> - <dd>Bitwise AND assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}</dt> - <dd>Bitwise XOR assignment.</dd> - <dt>{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}</dt> - <dd>Bitwise OR assignment.</dd> - <dt>{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> - {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> - <dd> - <p>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.</p> - </dd> -</dl> - -<h3 id="Comma_operator">Comma operator</h3> - -<dl> - <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> - <dd>The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.</dd> -</dl> - -<h3 id="Non-standard_features">Non-standard features</h3> - -<dl> - <dt>{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}</dt> - <dd>The <code>function</code> 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.</dd> - <dt>{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}</dt> - <dd>The expression closure syntax is a shorthand for writing simple function.</dd> - <dt>{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}</dt> - <dd>Array comprehensions.</dd> - <dt>{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}</dt> - <dd>Generator comprehensions.</dd> -</dl> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('ES1', '#sec-11', 'Expressions')}}</td> - <td>{{Spec2('ES1')}}</td> - <td>Initial definition</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-11', 'Expressions')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td></td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>New: Spread operator, destructuring assignment, <code>super</code> keyword.</td> - </tr> - <tr> - <td>{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> - <td>{{Spec2('ESDraft')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">Operator precedence</a></li> -</ul> 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 ---- -<div>{{jsSidebar("Statements")}}</div> - -<p>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.</p> - -<h2 id="Statements_and_declarations_by_category">Statements and declarations by category</h2> - -<p>For an alphabetical listing see the sidebar on the left.</p> - -<h3 id="Control_flow">Control flow</h3> - -<dl> - <dt>{{jsxref("Statements/block", "Block")}}</dt> - <dd>A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.</dd> - <dt>{{jsxref("Statements/break", "break")}}</dt> - <dd>Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.</dd> - <dt>{{jsxref("Statements/continue", "continue")}}</dt> - <dd>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.</dd> - <dt>{{jsxref("Statements/Empty", "Empty")}}</dt> - <dd>An empty statement is used to provide no statement, although the JavaScript syntax would expect one.</dd> - <dt>{{jsxref("Statements/if...else", "if...else")}}</dt> - <dd>Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.</dd> - <dt>{{jsxref("Statements/switch", "switch")}}</dt> - <dd>Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.</dd> - <dt>{{jsxref("Statements/throw", "throw")}}</dt> - <dd>Throws a user-defined exception.</dd> - <dt>{{jsxref("Statements/try...catch", "try...catch")}}</dt> - <dd>Marks a block of statements to try, and specifies a response, should an exception be thrown.</dd> -</dl> - -<h3 id="Declarations">Declarations</h3> - -<dl> - <dt>{{jsxref("Statements/var", "var")}}</dt> - <dd>Declares a variable, optionally initializing it to a value.</dd> - <dt>{{experimental_inline}} {{jsxref("Statements/let", "let")}}</dt> - <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> - <dt>{{experimental_inline}} {{jsxref("Statements/const", "const")}}</dt> - <dd>Declares a read-only named constant.</dd> -</dl> - -<h3 id="Functions_and_classes">Functions and classes</h3> - -<dl> - <dt>{{jsxref("Statements/function", "function")}}</dt> - <dd>Declares a function with the specified parameters.</dd> - <dt>{{experimental_inline}} {{jsxref("Statements/function*", "function*")}}</dt> - <dd>Generators functions enable writing <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">iterators</a> more easily.</dd> - <dt>{{jsxref("Statements/return", "return")}}</dt> - <dd>Specifies the value to be returned by a function.</dd> - <dt>{{experimental_inline}} {{jsxref("Statements/class", "class")}}</dt> - <dd>Declares a class.</dd> -</dl> - -<h3 id="Iterations">Iterations</h3> - -<dl> - <dt>{{jsxref("Statements/do...while", "do...while")}}</dt> - <dd>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.</dd> - <dt>{{jsxref("Statements/for", "for")}}</dt> - <dd>Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.</dd> - <dt>{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}</dt> - <dd>Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.</dd> - <dt>{{jsxref("Statements/for...in", "for...in")}}</dt> - <dd>Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.</dd> - <dt>{{experimental_inline}} {{jsxref("Statements/for...of", "for...of")}}</dt> - <dd>Iterates over iterable objects (including <a href="https://developer.mozilla.org/en-US/docs/Core_JavaScript_1.5_Reference/Global_Objects/Array" title="Array">arrays</a>, array-like objects, <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Iterators_and_Generators" title="Iterators and generators">iterators and generators</a>), invoking a custom iteration hook with statements to be executed for the value of each distinct property.</dd> - <dt>{{jsxref("Statements/while", "while")}}</dt> - <dd>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.</dd> -</dl> - -<h3 id="Others">Others</h3> - -<dl> - <dt>{{jsxref("Statements/debugger", "debugger")}}</dt> - <dd>Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.</dd> - <dt>{{experimental_inline}} {{jsxref("Statements/export", "export")}}</dt> - <dd>Used to export functions to make them available for imports in external modules, another scripts.</dd> - <dt>{{experimental_inline}} {{jsxref("Statements/import", "import")}}</dt> - <dd>Used to import functions exported from an external module, another script.</dd> - <dt>{{jsxref("Statements/label", "label")}}</dt> - <dd>Provides a statement with an identifier that you can refer to using a <code>break</code> or <code>continue</code> statement.</dd> -</dl> - -<dl> - <dt>{{deprecated_inline}} {{jsxref("Statements/with", "with")}}</dt> - <dd>Extends the scope chain for a statement.</dd> -</dl> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>ECMAScript 1st Edition.</td> - <td>Standard</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('ES5.1', '#sec-12', 'Statements')}}</td> - <td>{{Spec2('ES5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> - <td>{{Spec2('ES6')}}</td> - <td>New: function*, let, for...of, yield, class</td> - </tr> - </tbody> -</table> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Operators</a></li> -</ul> |