From ed2c9751e26d161ad81d86a8d50985cb964d30a1 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:47:01 +0100 Subject: unslug fa: move --- .../control_flow_and_error_handling/index.html | 424 ++++++++++++ .../guide/details_of_the_object_model/index.html | 718 +++++++++++++++++++++ files/fa/web/javascript/guide/functions/index.html | 648 +++++++++++++++++++ .../javascript/guide/grammar_and_types/index.html | 673 +++++++++++++++++++ files/fa/web/javascript/guide/index.html | 107 +++ .../web/javascript/guide/introduction/index.html | 138 ++++ .../control_flow_and_error_handling/index.html" | 424 ------------ .../details_of_the_object_model/index.html" | 718 --------------------- .../functions/index.html" | 648 ------------------- .../grammar_and_types/index.html" | 673 ------------------- .../index.html" | 107 --- .../index.html" | 138 ---- 12 files changed, 2708 insertions(+), 2708 deletions(-) create mode 100644 files/fa/web/javascript/guide/control_flow_and_error_handling/index.html create mode 100644 files/fa/web/javascript/guide/details_of_the_object_model/index.html create mode 100644 files/fa/web/javascript/guide/functions/index.html create mode 100644 files/fa/web/javascript/guide/grammar_and_types/index.html create mode 100644 files/fa/web/javascript/guide/index.html create mode 100644 files/fa/web/javascript/guide/introduction/index.html delete mode 100644 "files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/control_flow_and_error_handling/index.html" delete mode 100644 "files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/details_of_the_object_model/index.html" delete mode 100644 "files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/functions/index.html" delete mode 100644 "files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/grammar_and_types/index.html" delete mode 100644 "files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/index.html" delete mode 100644 "files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/\331\205\331\202\330\257\331\205\331\207/index.html" (limited to 'files/fa/web/javascript') 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..1b3edc9c8a --- /dev/null +++ b/files/fa/web/javascript/guide/control_flow_and_error_handling/index.html @@ -0,0 +1,424 @@ +--- +title: Control flow and error handling +slug: Web/JavaScript/راهنما/Control_flow_and_error_handling +translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
+ +

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

+ +

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

+ +

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

+ +

Block statement

+ +

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

+ +
{
+  statement_1;
+  statement_2;
+  .
+  .
+  .
+  statement_n;
+}
+
+ +

Example

+ +

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

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

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

+ +

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

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

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

+ +

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

+ +

Conditional statements

+ +

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

+ +

if...else statement

+ +

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

+ +

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

+ +

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

+ +

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

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

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

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

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

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

Falsy values

+ +

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

+ + + +

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

+ +

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

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

Example

+ +

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

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

switch statement

+ +

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

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

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

+ +

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

+ +

Example

+ +

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

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

Exception handling statements

+ +

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

+ + + +

Exception types

+ +

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

+ + + +

throw statement

+ +

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

+ +
throw expression;
+
+ +

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

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

try...catch statement

+ +

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

+ +

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

+ +

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

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

The catch block

+ +

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

+ +
catch (catchID) {
+  statements
+}
+
+ +

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

+ +

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

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

The finally block

+ +

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

+ +

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

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

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

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

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

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

Nesting try...catch statements

+ +

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

+ +

Utilizing Error objects

+ +

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

+ +

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

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

Promises

+ +

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

+ +

A Promise is in one of these states:

+ + + +

+ +

Loading an image with XHR

+ +

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

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

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

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

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

+ +

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

+ +

Class-based vs. prototype-based languages

+ +

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

+ + + +

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

+ +

تعریف یک کلاس

+ +

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

+ +

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

+ +
+

Note that ECMAScript 2015 introduces a class declaration:

+ +
+

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

+
+
+ +

Subclasses and inheritance

+ +

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

+ +

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

+ +

Adding and removing properties

+ +

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

+ +

Summary of differences

+ +

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

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

The employee example

+ +

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

+ +
+
+

A simple object hierarchy with the following objects:

+ +

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

Creating the hierarchy

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

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

JavaScript ** (use this instead)

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

Java

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

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

+ +

JavaScript

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

Java

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

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

+ +

JavaScript

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

Java

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

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

+ +
+

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

+
+ +

Creating objects with simple definitions

+ +
+

Object hierarchy

+ +

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

+ +

+ +

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

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

Object properties

+ +

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

+ +

Inheriting properties

+ +

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

+ +
var mark = new WorkerBee;
+
+ +

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

+ +

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

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

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

+ +

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

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

Adding properties

+ +

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

+ +
mark.bonus = 3000;
+
+ +

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

+ +

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

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

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

+ +


+ Adding properties

+ +

More flexible constructors

+ +

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

+ +


+ Specifying properties in a constructor, take 1

+ +

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

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

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

+ +
this.name = name || '';
+
+ +

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

+ +
+

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

+
+ +

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

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

Jane's properties are now:

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

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

+ +

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

+ +


+ Specifying properties in a constructor, take 2

+ +

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

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

Suppose you create a new Engineer object as follows:

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

JavaScript follows these steps:

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

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

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

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

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

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

+ +

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

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

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

+ +

Property inheritance revisited

+ +

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

+ +

Local versus inherited values

+ +

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

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

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

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

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

+ +
var amy = new WorkerBee;
+
+ +

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

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

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

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

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

+ +

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

+ +

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

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

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

+ +

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

+ +

Determining instance relationships

+ +

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

+ +

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

+ +

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

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

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

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

With this object, the following statements are all true:

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

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

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

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

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

But the following expression is false:

+ +
instanceOf(chris, SalesPerson)
+
+ +

Global information in constructors

+ +

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

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

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

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

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

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

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

+ +

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

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

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

+ +

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

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

No multiple inheritance

+ +

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

+ +

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

+ +

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

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

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

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

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

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

The dennis object does not inherit this new property.

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

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

+ +

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

+ +

Defining functions

+ +

Function declarations

+ +

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

+ + + +

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

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

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

+ +
return number * number;
+
+ +

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

+ +

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

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

Function expressions

+ +

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

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

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

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

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

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

The following code:

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

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

+ +

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

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

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

+ +

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

+ +

Calling functions

+ +

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

+ +
square(5);
+
+ +

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

+ +

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

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

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

+ +
+

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

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

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

+ +

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

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

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

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

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

+ +

Function scope

+ +

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

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

Scope and the function stack

+ +

Recursion

+ +

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

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

For example, consider the following function definition:

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

Within the function body, the following are all equivalent:

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

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

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

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

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

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

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

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

+ +

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

+ +

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

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

Nested functions and closures

+ +

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

+ +

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

+ +

To summarize:

+ + + + + +

The following example shows nested functions:

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

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

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

Preservation of variables

+ +

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

+ +

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

+ +

Multiply-nested functions

+ +

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

+ +

Consider the following example:

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

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

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

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

+ +

Name conflicts

+ +

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

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

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

+ +

Closures

+ +

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

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

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

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

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

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

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

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

Using the arguments object

+ +

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

+ +
arguments[i]
+
+ +

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

+ +

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

+ +

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

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

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

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

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

+
+ +

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

+ +

Function parameters

+ +

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

+ +

Default parameters

+ +

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

+ +

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

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

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

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

For more details, see default parameters in the reference.

+ +

Rest parameters

+ +

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

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

Arrow functions

+ +

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

+ +

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

+ +

Shorter functions

+ +

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

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

Lexical this

+ +

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

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

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

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

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

+ +

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

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

Predefined functions

+ +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+
+
+ +

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

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

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

+ +

مقدمه

+ +

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

+ +

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

+ +

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

+ +

توضیح (comment)

+ +

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

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

اعلان‌ها (Declarations)

+ +

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

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

متغیرها

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ + + +

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

+ +

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

+ +

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

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

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

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

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

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

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

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

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

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

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

+ +

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

+ +

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

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

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

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

Variable hoisting

+ +

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

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

The above examples will be interpreted the same as:

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

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

+ +

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

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

Function hoisting

+ +

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

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

Global variables

+ +

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

+ +

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

+ +

Constants

+ +

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

+ +
const PI = 3.14;
+
+ +

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

+ +

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

+ +

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

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

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

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

Data structures and types

+ +

Data types

+ +

The latest ECMAScript standard defines seven data types:

+ + + +

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

+ +

Data type conversion

+ +

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

+ +
var answer = 42;
+
+ +

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

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

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

+ +

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

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

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

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

Converting strings to numbers

+ +

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

+ + + +

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

+ +

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

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

Literals

+ +

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

+ + + +

Array literals

+ +

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

+ +

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

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

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

+
+ +

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

+ +

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

+ +

Extra commas in array literals

+ +

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

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

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

+ +

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

+ +
+

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

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

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

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

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

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

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

+ +

Boolean literals

+ +

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

+ +

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

+ +

Integers

+ +

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

+ + + +

Some examples of integer literals are:

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

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

+ +

Floating-point literals

+ +

A floating-point literal can have the following parts:

+ + + +

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

+ +

More succinctly, the syntax is:

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

For example:

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

Object literals

+ +

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

+ +

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

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

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

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

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

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

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

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

Please note:

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

RegExp literals

+ +

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

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

String literals

+ +

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

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

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

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

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

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

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

+ +

Using special characters in strings

+ +

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

+ +
"one line \n another line"
+
+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Table: JavaScript special characters

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

Escaping characters

+ +

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

+ +

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

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

The result of this would be:

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

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

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

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

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

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

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

More information

+ +

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

+ + + +

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

+ +

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

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

{{jsSidebar("JavaScript Guide")}}

+ +
+

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

+
+ + + + + +

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

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

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

+ +

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

+ +

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

+ + + +

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

+ +

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

+ +

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

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

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

+ +

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

+ +

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

+ + + +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

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

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

کنسول وب

+ +

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

+ +

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

+ +

+ +

Scratchpad

+ +

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

+ +

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

+ +

+ +

Hello world

+ +

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

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

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

+ +

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

+ +

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

diff --git "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/control_flow_and_error_handling/index.html" "b/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/control_flow_and_error_handling/index.html" deleted file mode 100644 index 1b3edc9c8a..0000000000 --- "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/control_flow_and_error_handling/index.html" +++ /dev/null @@ -1,424 +0,0 @@ ---- -title: Control flow and error handling -slug: Web/JavaScript/راهنما/Control_flow_and_error_handling -translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
- -

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

- -

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

- -

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

- -

Block statement

- -

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

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

Example

- -

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

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

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

- -

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

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

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

- -

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

- -

Conditional statements

- -

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

- -

if...else statement

- -

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

- -

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

- -

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

- -

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

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

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

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

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

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

Falsy values

- -

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

- - - -

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

- -

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

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

Example

- -

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

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

switch statement

- -

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

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

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

- -

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

- -

Example

- -

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

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

Exception handling statements

- -

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

- - - -

Exception types

- -

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

- - - -

throw statement

- -

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

- -
throw expression;
-
- -

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

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

try...catch statement

- -

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

- -

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

- -

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

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

The catch block

- -

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

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

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

- -

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

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

The finally block

- -

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

- -

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

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

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

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

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

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

Nesting try...catch statements

- -

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

- -

Utilizing Error objects

- -

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

- -

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

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

Promises

- -

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

- -

A Promise is in one of these states:

- - - -

- -

Loading an image with XHR

- -

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

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

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

- -
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
diff --git "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/details_of_the_object_model/index.html" "b/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/details_of_the_object_model/index.html" deleted file mode 100644 index 5e523e9124..0000000000 --- "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/details_of_the_object_model/index.html" +++ /dev/null @@ -1,718 +0,0 @@ ---- -title: Details of the object model -slug: Web/JavaScript/راهنما/Details_of_the_Object_Model -translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}
- -

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

- -

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

- -

Class-based vs. prototype-based languages

- -

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

- - - -

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

- -

تعریف یک کلاس

- -

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

- -

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

- -
-

Note that ECMAScript 2015 introduces a class declaration:

- -
-

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

-
-
- -

Subclasses and inheritance

- -

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

- -

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

- -

Adding and removing properties

- -

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

- -

Summary of differences

- -

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

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

The employee example

- -

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

- -
-
-

A simple object hierarchy with the following objects:

- -

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

Creating the hierarchy

- -

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

- -

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

- -

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

- -

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

- -

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

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

JavaScript ** (use this instead)

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

Java

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

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

- -

JavaScript

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

Java

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

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

- -

JavaScript

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

Java

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

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

- -
-

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

-
- -

Creating objects with simple definitions

- -
-

Object hierarchy

- -

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

- -

- -

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

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

Object properties

- -

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

- -

Inheriting properties

- -

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

- -
var mark = new WorkerBee;
-
- -

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

- -

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

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

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

- -

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

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

Adding properties

- -

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

- -
mark.bonus = 3000;
-
- -

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

- -

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

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

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

- -


- Adding properties

- -

More flexible constructors

- -

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

- -


- Specifying properties in a constructor, take 1

- -

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

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

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

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

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

- -
-

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

-
- -

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

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

Jane's properties are now:

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

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

- -

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

- -


- Specifying properties in a constructor, take 2

- -

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

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

Suppose you create a new Engineer object as follows:

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

JavaScript follows these steps:

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

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

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

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

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

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

- -

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

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

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

- -

Property inheritance revisited

- -

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

- -

Local versus inherited values

- -

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

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

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

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

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

- -
var amy = new WorkerBee;
-
- -

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

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

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

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

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

- -

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

- -

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

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

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

- -

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

- -

Determining instance relationships

- -

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

- -

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

- -

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

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

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

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

With this object, the following statements are all true:

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

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

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

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

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

But the following expression is false:

- -
instanceOf(chris, SalesPerson)
-
- -

Global information in constructors

- -

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

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

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

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

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

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

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

- -

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

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

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

- -

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

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

No multiple inheritance

- -

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

- -

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

- -

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

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

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

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

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

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

The dennis object does not inherit this new property.

- -
{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}
diff --git "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/functions/index.html" "b/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/functions/index.html" deleted file mode 100644 index 626ea544bf..0000000000 --- "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/functions/index.html" +++ /dev/null @@ -1,648 +0,0 @@ ---- -title: Functions -slug: Web/JavaScript/راهنما/Functions -translation_of: Web/JavaScript/Guide/Functions ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}
- -

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

- -

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

- -

Defining functions

- -

Function declarations

- -

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

- - - -

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

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

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

- -
return number * number;
-
- -

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

- -

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

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

Function expressions

- -

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

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

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

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

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

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

The following code:

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

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

- -

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

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

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

- -

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

- -

Calling functions

- -

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

- -
square(5);
-
- -

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

- -

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

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

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

- -
-

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

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

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

- -

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

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

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

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

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

- -

Function scope

- -

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

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

Scope and the function stack

- -

Recursion

- -

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

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

For example, consider the following function definition:

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

Within the function body, the following are all equivalent:

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

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

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

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

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

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

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

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

- -

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

- -

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

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

Nested functions and closures

- -

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

- -

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

- -

To summarize:

- - - - - -

The following example shows nested functions:

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

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

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

Preservation of variables

- -

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

- -

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

- -

Multiply-nested functions

- -

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

- -

Consider the following example:

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

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

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

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

- -

Name conflicts

- -

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

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

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

- -

Closures

- -

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

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

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

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

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

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

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

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

Using the arguments object

- -

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

- -
arguments[i]
-
- -

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

- -

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

- -

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

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

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

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

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

-
- -

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

- -

Function parameters

- -

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

- -

Default parameters

- -

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

- -

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

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

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

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

For more details, see default parameters in the reference.

- -

Rest parameters

- -

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

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

Arrow functions

- -

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

- -

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

- -

Shorter functions

- -

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

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

Lexical this

- -

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

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

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

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

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

- -

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

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

Predefined functions

- -

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

-
-
- -

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

diff --git "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/grammar_and_types/index.html" "b/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/grammar_and_types/index.html" deleted file mode 100644 index 7ccb432c33..0000000000 --- "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/grammar_and_types/index.html" +++ /dev/null @@ -1,673 +0,0 @@ ---- -title: گرامر و انواع -slug: Web/JavaScript/راهنما/Grammar_and_types -translation_of: Web/JavaScript/Guide/Grammar_and_types ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
- -

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

- -

مقدمه

- -

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

- -

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

- -

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

- -

توضیح (comment)

- -

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

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

اعلان‌ها (Declarations)

- -

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

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

متغیرها

- -

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

- -

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

- -

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

- -

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

- -

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

- -

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

- - - -

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

- -

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

- -

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

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

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

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

رفتار مقدار undefined در ارزیابی عبارات منطقی مانند false است. برای مثال، در کد زیر تابع  myFunction  اجرا خواهد شد چون المان myArray تعریف‌نشده است:

- -
var myArray = [];
-if (!myArray[0]) myFunction();
-
- -

در یک عبارت عددی مقدار undefined به  NaN تبدیل می‌شود.

- -
var a;
-a + 2;  // Evaluates to NaN
- -

وقتی یک متغیر {{jsxref("null")}} را ارزیابی می‌کنید، در یک عبارت عددی دارای مقدارصفر و در یک عبارت منطقی دارای مقدار false خواهد بود. برای مثال:

- -
var n = null;
-console.log(n * 32); // Will log 0 to the console
-
- -

قلمرو متغیر (Variable Scope)

- -

When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.

- -

JavaScript before ECMAScript 2015 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

- -
if (true) {
-  var x = 5;
-}
-console.log(x);  // x is 5
-
- -

This behavior changes, when using the let declaration introduced in ECMAScript 2015.

- -
if (true) {
-  let y = 5;
-}
-console.log(y);  // ReferenceError: y is not defined
-
- -

Variable hoisting

- -

Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that are hoisted will return a value of undefined. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.

- -
/**
- * Example 1
- */
-console.log(x === undefined); // true
-var x = 3;
-
-/**
- * Example 2
- */
-// will return a value of undefined
-var myvar = "my value";
-
-(function() {
-  console.log(myvar); // undefined
-  var myvar = "local value";
-})();
-
- -

The above examples will be interpreted the same as:

- -
/**
- * Example 1
- */
-var x;
-console.log(x === undefined); // true
-x = 3;
-
-/**
- * Example 2
- */
-var myvar = "my value";
-
-(function() {
-  var myvar;
-  console.log(myvar); // undefined
-  myvar = "local value";
-})();
-
- -

Because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.

- -

In ECMAScript 2015, let (const) will not hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a {{jsxref("ReferenceError")}}. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

- -
console.log(x); // ReferenceError
-let x = 3;
- -

Function hoisting

- -

For functions, only function declaration gets hoisted to the top and not the function expression.

- -
/* Function declaration */
-
-foo(); // "bar"
-
-function foo() {
-  console.log("bar");
-}
-
-
-/* Function expression */
-
-baz(); // TypeError: baz is not a function
-
-var baz = function() {
-  console.log("bar2");
-};
-
- -

Global variables

- -

Global variables are in fact properties of the global object. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the window.variable syntax.

- -

Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber.

- -

Constants

- -

You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.

- -
const PI = 3.14;
-
- -

A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.

- -

The scope rules for constants are the same as those for let block scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.

- -

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

- -
// THIS WILL CAUSE AN ERROR
-function f() {};
-const f = 5;
-
-// THIS WILL CAUSE AN ERROR ALSO
-function f() {
-  const g = 5;
-  var g;
-
-  //statements
-}
-
- -

However, the properties of objects assigned to constants are not protected, so the following statement is executed without problems.

- -
const MY_OBJECT = {"key": "value"};
-MY_OBJECT.key = "otherValue";
- -

Data structures and types

- -

Data types

- -

The latest ECMAScript standard defines seven data types:

- - - -

Although these data types are a relatively small amount, they enable you to perform useful functions with your applications. {{jsxref("Object", "Objects")}} and {{jsxref("Function", "functions")}} are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.

- -

Data type conversion

- -

JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:

- -
var answer = 42;
-
- -

And later, you could assign the same variable a string value, for example:

- -
answer = "Thanks for all the fish...";
-
- -

Because JavaScript is dynamically typed, this assignment does not cause an error message.

- -

In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:

- -
x = "The answer is " + 42 // "The answer is 42"
-y = 42 + " is the answer" // "42 is the answer"
-
- -

In statements involving other operators, JavaScript does not convert numeric values to strings. For example:

- -
"37" - 7 // 30
-"37" + 7 // "377"
-
- -

Converting strings to numbers

- -

In the case that a value representing a number is in memory as a string, there are methods for conversion.

- - - -

parseInt will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for parseInt is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.

- -

An alternative method of retrieving a number from a string is with the + (unary plus) operator:

- -
"1.1" + "1.1" = "1.11.1"
-(+"1.1") + (+"1.1") = 2.2
-// Note: the parentheses are added for clarity, not required.
- -

Literals

- -

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

- - - -

Array literals

- -

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

- -

The following example creates the coffees array with three elements and a length of three:

- -
var coffees = ["French Roast", "Colombian", "Kona"];
-
- -
-

Note : An array literal is a type of object initializer. See Using Object Initializers.

-
- -

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

- -

Array literals are also Array objects. See {{jsxref("Array")}} and Indexed collections for details on Array objects.

- -

Extra commas in array literals

- -

You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with undefined for the unspecified elements. The following example creates the fish array:

- -
var fish = ["Lion", , "Angel"];
-
- -

This array has two elements with values and one empty element (fish[0] is "Lion", fish[1] is undefined, and fish[2] is "Angel").

- -

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element.

- -
-

Note : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

-
- -
var myList = ['home', , 'school', ];
-
- -

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

- -
var myList = [ , 'home', , 'school'];
-
- -

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

- -
var myList = ['home', , 'school', , ];
-
- -

Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as undefined will increase your code's clarity and maintainability.

- -

Boolean literals

- -

The Boolean type has two literal values: true and false.

- -

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See {{jsxref("Boolean")}} for more information.

- -

Integers

- -

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

- - - -

Some examples of integer literals are:

- -
0, 117 and -345 (decimal, base 10)
-015, 0001 and -0o77 (octal, base 8)
-0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
-0b11, 0b0011 and -0b11 (binary, base 2)
-
- -

For more information, see Numeric literals in the Lexical grammar reference.

- -

Floating-point literals

- -

A floating-point literal can have the following parts:

- - - -

The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").

- -

More succinctly, the syntax is:

- -
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
-
- -

For example:

- -
3.1415926
--.123456789
--3.1E+12
-.1e-23
-
- -

Object literals

- -

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

- -

The following is an example of an object literal. The first element of the car object defines a property, myCar, and assigns to it a new string, "Saturn"; the second element, the getCar property, is immediately assigned the result of invoking the function (carTypes("Honda")); the third element, the special property, uses an existing variable (sales).

- -
var sales = "Toyota";
-
-function carTypes(name) {
-  if (name === "Honda") {
-    return name;
-  } else {
-    return "Sorry, we don't sell " + name + ".";
-  }
-}
-
-var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales };
-
-console.log(car.myCar);   // Saturn
-console.log(car.getCar);  // Honda
-console.log(car.special); // Toyota
-
- -

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

- -
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
-
-console.log(car.manyCars.b); // Jeep
-console.log(car[7]); // Mazda
-
- -

Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript {{Glossary("Identifier","identifier")}} or number, it must be enclosed in quotes. Property names that are not valid identifiers also cannot be accessed as a dot (.) property, but can be accessed and set with the array-like notation("[]").

- -
var unusualPropertyNames = {
-  "": "An empty string",
-  "!": "Bang!"
-}
-console.log(unusualPropertyNames."");   // SyntaxError: Unexpected string
-console.log(unusualPropertyNames[""]);  // An empty string
-console.log(unusualPropertyNames.!);    // SyntaxError: Unexpected token !
-console.log(unusualPropertyNames["!"]); // Bang!
- -

In ES2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

- -
var obj = {
-    // __proto__
-    __proto__: theProtoObj,
-    // Shorthand for ‘handler: handler’
-    handler,
-    // Methods
-    toString() {
-     // Super calls
-     return "d " + super.toString();
-    },
-    // Computed (dynamic) property names
-    [ 'prop_' + (() => 42)() ]: 42
-};
- -

Please note:

- -
var foo = {a: "alpha", 2: "two"};
-console.log(foo.a);    // alpha
-console.log(foo[2]);   // two
-//console.log(foo.2);  // Error: missing ) after argument list
-//console.log(foo[a]); // Error: a is not defined
-console.log(foo["a"]); // alpha
-console.log(foo["2"]); // two
-
- -

RegExp literals

- -

A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.

- -
var re = /ab+c/;
- -

String literals

- -

A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:

- -
"foo"
-'bar'
-"1234"
-"one line \n another line"
-"John's cat"
-
- -

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal:

- -
console.log("John's cat".length)
-// Will print the number of symbols in the string including whitespace.
-// In this case, 10.
-
- -

In ES2015, template literals are also available. Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.

- -
// Basic literal string creation
-`In JavaScript '\n' is a line-feed.`
-
-// Multiline strings
-`In JavaScript template strings can run
- over multiple lines, but double and single
- quoted strings cannot.`
-
-// String interpolation
-var name = "Bob", time = "today";
-`Hello ${name}, how are you ${time}?`
-
-// Construct an HTTP request prefix is used to interpret the replacements and construction
-POST`http://foo.org/bar?a=${a}&b=${b}
-     Content-Type: application/json
-     X-Credentials: ${credentials}
-     { "foo": ${foo},
-       "bar": ${bar}}`(myOnReadyStateChangeHandler);
- -

You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on String objects.

- -

Using special characters in strings

- -

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

- -
"one line \n another line"
-
- -

The following table lists the special characters that you can use in JavaScript strings.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Table: JavaScript special characters

-
CharacterMeaning
\0Null Byte
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.
\u{XXXXX}Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.
- -

Escaping characters

- -

For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

- -

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-console.log(quote);
-
- -

The result of this would be:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
-
- -

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

- -
var home = "c:\\temp";
-
- -

You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.

- -
var str = "this string \
-is broken \
-across multiple\
-lines."
-console.log(str);   // this string is broken across multiplelines.
-
- -

Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line:

- -
var poem =
-"Roses are red,\n\
-Violets are blue.\n\
-Sugar is sweet,\n\
-and so is foo."
-
- -

More information

- -

This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:

- - - -

In the next chapter, we will have a look at control flow constructs and error handling.

- -

{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

diff --git "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/index.html" "b/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/index.html" deleted file mode 100644 index 6ebfec2533..0000000000 --- "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/index.html" +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: راهنمای جاوا اسکریپت -slug: Web/JavaScript/راهنما -translation_of: Web/JavaScript/Guide ---- -

{{jsSidebar("JavaScript Guide")}}

- -
-

راهنمای javascript یک مرور اجمالی بر روی این زبان داشته و به شما طریقه استفاده از جاوا اسکریپت را نشان می دهد.  اگر می خواهید به طور کلی برنامه نویسی یا جاوا اسکریپت را شروع کنید, از مقالات ما در محیط آموزشی کمک بگیرید. اگر به اطلاعات کامل درباره ویژگی های یک زبان نیاز دارید، نگاهی به مرجع جاوا اسکریپت داشته باشید

-
- - - - - -

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/\331\205\331\202\330\257\331\205\331\207/index.html" "b/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/\331\205\331\202\330\257\331\205\331\207/index.html" deleted file mode 100644 index 3e8b0f1cff..0000000000 --- "a/files/fa/web/javascript/\330\261\330\247\331\207\331\206\331\205\330\247/\331\205\331\202\330\257\331\205\331\207/index.html" +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: مقدمه -slug: Web/JavaScript/راهنما/مقدمه -tags: - - اکما اسکریپت - - جاوا اسکریپت -translation_of: Web/JavaScript/Guide/Introduction ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
- -

در این فصل به مباحث مقدماتی جاوا اسکریپت پرداخته و برخی از مفاهیم اساسی آن را بیان می کنیم . 

- -

آنچه که شما باید از قبل بدانید

- -

این آموزش فرض را بر این گرفته که شما پیش زمینه های زیر را دارا هستید:

- - - -

مقداری تجربه ی برنامه نویسی . اگر شما به تازگی وارد برنامه نویسی شده اید ، سعی کنید ابتدا از لینک های آموزشی که در صفحه ی اصلی هست به لینک درباره ی جاوا اسکریپت بروید.

- -

کجا اطلاعات جاوا اسکریپت را پیدا کنید

- -

مستندات جاوا اسکریپت در MDN شامل موارد زیر است:

- -
    -
  1. یادگیری وب: اطلاعاتی را برای افراد تازه کار فراهم می کند و همچنین مفاهیم پایه برنامه نویسی و اینترنت را معرفی می کند
  2. -
  3. راهنمای جاوا اسکریپت: (این راهنمایی) یک دیدکلی را از زبان جاوا اسکریپت و اشیای آن ارائه می کند
  4. -
  5. مرجع جاوا اسکریپت: یک مرجع همراه با جزئیات برای زبان جاوا اسکریپت فراهم می کند
  6. -
- -

جاوا اسکریپت چیست؟

- -

جاوا اسکریپت یک زبان با بسترمتقاطع(چند پلتفرمی) و شی گرای اسکریپتی است. این زبان کوچک و سبک است. در محیط میزبان (برای مثال یک مرورگر) جاوا اسکریپت می تواند به اشیای محیط متصل شده و کنترل به وسیله برنامه نویسی را برای آن محیط فراهم می کند.

- -

جاوا اسکریپت شامل یک کتابخانه استاندارد اشیا است مانند Array، Date و Math، مجموعه پایه ای از عناصر زبان مثل عملگرها، ساختارهای کنترلی و عبارات. هسته ی زبان جاوا اسکریپت می تواند برای اهداف مختلفی توسعه داده شود. برای این منظور از جاوا اسکریپت به همراه اشیایی اضافی استفاده می شود برای مثال:

- - - -

جاوا اسکریپت و جاوا

- -

جاوااسکریپت و جاوا از بعضی جهات با هم مشابه

- -

In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.

- -

JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.

- -

Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.

- -

In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript compared to Java
JavaScriptJava
Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically.Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.
Variable data types are not declared (dynamic typing).Variable data types must be declared (static typing).
Cannot automatically write to hard disk.Can automatically write to hard disk.
- -

For more information on the differences between JavaScript and Java, see the chapter Details of the object model.

- -

مشخصات جاوا اسکریپت و اکما اسکریپت

- -

جاوا اسکریپت در Ecma International استاندارد شده است —اتحادیه اروپا برای استاندارد سازی سیستم های اطلاعاتی و ارتباطی (ECMA مخفف انجمن سازندگان کامپیوتری اروپا) بود تا یک زبان برنامه نویسی استاندارد مبتنی بر جاوا اسکریپت را ارائه کند.

- -

این نسخه استاندارد از جاوا اسکریپت، به نام اکما اسکریپت ، در تمامی برنامه هایی که از استاندارد پشتیبانی می کنند، یکسان عمل می کند. شرکت ها می توانند از استاندارد زبان باز برای توسعه جاوا اسکریپت خود استفاده کنند. استاندارد اکما اسکریپت در مشخصات ECMA-262 مستند شده است. تازه ها در جاوا اسکریپت را برای کسب اطلاعات بیشتر در مورد نسخه های مختلف نسخه های خاص جاوا اسکریپت و اکما اسکریپت مشاهده کنید.

- -

The ECMA-262 standard is also approved by the ISO (International Organization for Standardization) as ISO-16262. You can also find the specification on the Ecma International website. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the World Wide Web Consortium (W3C) and/or WHATWG (Web Hypertext Application Technology Working Group). The DOM defines the way in which HTML document objects are exposed to your script. To get a better idea about the different technologies that are used when programming with JavaScript, consult the article JavaScript technologies overview.

- -

مستندات جاوا اسکریپت در مقایسه با مشخصات اکما اسکریپت

- -

مشخصات اکما اسکریپت مجموعه ای از الزامات برای پیاده سازی اکما اسکریپت است؛ اگر شما می خواهید ویژگی های زبان سازگار با استاندارد را در پیاده سازی اکما اسکریپت یا موتور خود (مانند SpiderMonkey در فایرفاکس یا v8 در Chrome) پیاده سازی کنید، مفید است.

- -

The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.

- -

The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.

- -

The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.

- -

شروع با جاوا اسکریپت

- -

Getting started with JavaScript is easy: all you need is a modern Web browser. This guide includes some JavaScript features which are only currently available in the latest versions of Firefox, so using the most recent version of Firefox is recommended.

- -

There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.

- -

کنسول وب

- -

The Web Console shows you information about the currently loaded Web page, and also includes a command line that you can use to execute JavaScript expressions in the current page.

- -

To open the Web Console (Ctrl+Shift+K), select "Web Console" from the "Developer" menu, which is under the "Tools" menu in Firefox. It appears at the bottom of the browser window. Along the bottom of the console is a command line that you can use to enter JavaScript, and the output appears in the pane above:

- -

- -

Scratchpad

- -

The Web Console is great for executing single lines of JavaScript, but although you can execute multiple lines, it's not very convenient for that, and you can't save your code samples using the Web Console. So for more complex examples Scratchpad is a better tool.

- -

To open Scratchpad (Shift+F4), select "Scratchpad" from the "Developer" menu, which is under the menu in Firefox. It opens in a separate window and is an editor that you can use to write and execute JavaScript in the browser. You can also save scripts to disk and load them from disk.

- -

- -

Hello world

- -

To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:

- -
function greetMe(yourName) {
-  alert("Hello " + yourName);
-}
-
-greetMe("World");
-
- -

Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!

- -

In the following pages, this guide will introduce you to the JavaScript syntax and language features, so that you will be able to write more complex applications.

- -

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

-- cgit v1.2.3-54-g00ecf