diff options
Diffstat (limited to 'files/fa/web/javascript/guide')
6 files changed, 2714 insertions, 0 deletions
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 new file mode 100644 index 0000000000..9d9f2db887 --- /dev/null +++ b/files/fa/web/javascript/guide/control_flow_and_error_handling/index.html @@ -0,0 +1,425 @@ +--- +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 new file mode 100644 index 0000000000..8562138526 --- /dev/null +++ b/files/fa/web/javascript/guide/details_of_the_object_model/index.html @@ -0,0 +1,719 @@ +--- +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 new file mode 100644 index 0000000000..5e4f1a8c63 --- /dev/null +++ b/files/fa/web/javascript/guide/functions/index.html @@ -0,0 +1,649 @@ +--- +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 new file mode 100644 index 0000000000..c42b672d21 --- /dev/null +++ b/files/fa/web/javascript/guide/grammar_and_types/index.html @@ -0,0 +1,674 @@ +--- +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 new file mode 100644 index 0000000000..ec38190108 --- /dev/null +++ b/files/fa/web/javascript/guide/index.html @@ -0,0 +1,108 @@ +--- +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 new file mode 100644 index 0000000000..8b047be839 --- /dev/null +++ b/files/fa/web/javascript/guide/introduction/index.html @@ -0,0 +1,139 @@ +--- +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> |