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 --- files/fa/web/api/canvas_api/tutorial/index.html | 180 ++++++ files/fa/web/api/htmlelement/innertext/index.html | 75 +++ files/fa/web/api/node/innertext/index.html | 75 --- files/fa/web/api/server-sent_events/index.html | 99 +++ files/fa/web/css/attribute_selectors/index.html | 182 ++++++ .../media_queries/using_media_queries/index.html | 331 ++++++++++ .../index.html" | 331 ---------- files/fa/web/css/type_selectors/index.html | 78 +++ files/fa/web/css/zoom/index.html | 134 ++++ .../index.html" | 78 --- .../index.html" | 182 ------ .../index.html" | 134 ---- files/fa/web/guide/html/html5/index.html | 155 +++++ files/fa/web/html/applying_color/index.html | 502 ++++++++++++++ files/fa/web/html/attributes/index.html | 607 +++++++++++++++++ .../index.html | 127 ---- .../index.html" | 502 -------------- .../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 ---- .../index.html" | 129 ---- 30 files changed, 5051 insertions(+), 4266 deletions(-) create mode 100644 files/fa/web/api/canvas_api/tutorial/index.html create mode 100644 files/fa/web/api/htmlelement/innertext/index.html delete mode 100644 files/fa/web/api/node/innertext/index.html create mode 100644 files/fa/web/api/server-sent_events/index.html create mode 100644 files/fa/web/css/attribute_selectors/index.html create mode 100644 files/fa/web/css/media_queries/using_media_queries/index.html delete mode 100644 "files/fa/web/css/media_queries/\330\247\330\250\330\262\330\247\330\261-\330\252\330\263\330\252-\330\261\330\263\330\247\331\206\331\207-\331\276\330\247\330\263\330\256\332\257\331\210/index.html" create mode 100644 files/fa/web/css/type_selectors/index.html create mode 100644 files/fa/web/css/zoom/index.html delete mode 100644 "files/fa/web/css/\330\247\331\206\330\252\330\256\330\247\330\250\332\257\330\261\331\200\331\206\331\210\330\271/index.html" delete mode 100644 "files/fa/web/css/\330\247\331\206\330\252\330\256\330\247\330\250\332\257\330\261\331\200\331\210\333\214\332\230\332\257\333\214/index.html" delete mode 100644 "files/fa/web/css/\330\250\330\262\330\261\332\257\331\206\331\205\330\247\333\214\333\214/index.html" create mode 100644 files/fa/web/guide/html/html5/index.html create mode 100644 files/fa/web/html/applying_color/index.html create mode 100644 files/fa/web/html/attributes/index.html delete mode 100644 files/fa/web/html/tips_for_authoring_fast-loading_html_pages/index.html delete mode 100644 "files/fa/web/html/\330\247\331\201\330\262\331\210\330\257\331\206_\330\261\331\206\332\257/index.html" 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" delete mode 100644 "files/fa/web/\330\254\330\247\331\210\330\247\330\247\330\263\332\251\330\261\333\214\331\276\330\252/index.html" (limited to 'files/fa/web') diff --git a/files/fa/web/api/canvas_api/tutorial/index.html b/files/fa/web/api/canvas_api/tutorial/index.html new file mode 100644 index 0000000000..2e74741940 --- /dev/null +++ b/files/fa/web/api/canvas_api/tutorial/index.html @@ -0,0 +1,180 @@ +--- +title: رسم گرافیک با Canvas +slug: HTML/Canvas/Drawing_Graphics_with_Canvas +translation_of: Web/API/Canvas_API/Tutorial +translation_of_original: Web/API/Canvas_API/Drawing_graphics_with_canvas +--- +
+

بخش عمده‌ای از این مطلب (به جز مستندات drawWindow) به صفحه‌ی اصلی آموزش Canvas منتقل شده است، بنابراین این صفحه نیز به احتمال زیاد به آن قسمت منتقل می‌شود تا از ایجاد محتوای تکراری جلوگیری شود.

+
+

مقدمه

+

با انتشار فایرفاکس ۱.۵، عنصر جدیدی از HTML برای برنامه‌نویسی حالت گرافیکی در فایرفاکس به وجود آمد. <canvas> بر اساس مستندات WHATWG برای Canvas پیاده‌سازی شده است که خود این مستندات نیز بر پایه‌ی عنصر <canvas> در مرورگر سافاری از اپل ایجاد شده است. از آن می‌توان برای ترسیم نمودار، عنصرهای واسط کاربری و سایر عنصرهای گرافیکی در مرورگر استفاده کرد.

+

<canvas> با ایجاد یک سطح ترسیمی با اندازه‌ی ثابت سبب می‌شود که یک یا چند فضای گرافیکی به وجود بیایند. در این مقاله ما بر روی فضای گرافیکی ۲ بعدی تمرکز می‌کنیم. برای گرافیک ۳ بعدی، شما باید از فضای گرافیکی WebGL استفاده کنید.

+

فضای گرافیکی ۲ بعدی

+

یک نمونه‌ی ساده

+

برای شروع، با نمونه‌ای ساده که دو مستطیل با فضای مشترک شفاف مشخص شده‌اند، آغاز می‌کنیم:

+

Example 1.

+
<html>
+ <head>
+  <script type="application/javascript">
+function draw() {
+ var canvas = document.getElementById("canvas");
+ var ctx = canvas.getContext("2d");
+
+ ctx.fillStyle = "rgb(200,0,0)";
+ ctx.fillRect (10, 10, 55, 50);
+
+ ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
+ ctx.fillRect (30, 30, 55, 50);
+}
+  </script>
+ </head>
+ <body onload="draw()">
+   <canvas id="canvas" width="300" height="300"></canvas>
+ </body>
+</html>
+
+

تابع draw با دریافت عنصر canvas فضای ۲ بعدی آن را مشخص می‌کند. شی ctx می‌تواند برای رسم گرافیک روی بوم استفاده شود. در این کد، دو مستطیل با تنظیمات fillStyle و fiilRect با فضای مشترک شفاف رسم می‌شوند. fillStyle دوم از rgba برای مشخص کردن شفافیت با رنگ مورد نظر، استفاده می‌کند.

+

fillRect برای رسم مستطیل، strokeRect برای رسم حاشیه‌های مستطیل و clearRect برای پاک‌کردن مستطیل استفاده می‌شوند. برای ایجاد شکل‌های پیچیده‌تر، از مسیرها استفاده می‌شود.

+

استفاده از مسیرها

+

تابع beginPath یک مسیر جدید را آغاز می‌کند و متدهای moveTo, lineTo, arcTo, arc و از این قبیل، بخش‌های مختلفی را به مسیر تعریف‌شده اضافه می‌کنند. مسیر ایجاد شده توسط تابع closePath بسته می‌شود. زمانی که یک مسیر ایجاد شود، شما می‌توانید با fill یا stroke فضای داخل یا حاشیه‌ی مسیر را روی بوم رسم کنید.

+

Example 2.

+
<html>
+ <head>
+  <script type="application/javascript">
+function draw() {
+  var canvas = document.getElementById("canvas");
+  var ctx = canvas.getContext("2d");
+
+  ctx.fillStyle = "red";
+
+  ctx.beginPath();
+  ctx.moveTo(30, 30);
+  ctx.lineTo(150, 150);
+  // was: ctx.quadraticCurveTo(60, 70, 70, 150); which is wrong.
+  ctx.bezierCurveTo(60, 70, 60, 70, 70, 150); // <- this is right formula for the image on the right ->
+  ctx.lineTo(30, 30);
+  ctx.fill();
+}
+   </script>
+ </head>
+ <body onload="draw()">
+   <canvas id="canvas" width="300" height="300"></canvas>
+ </body>
+</html>
+
+

فراخوانی هر یک از توابع fill یا stroke، روی مسیر فعلی تاثیر می‌گذارد. اگر دوباره قصد رنگ‌آمیزی یا ایجاد حاشیه در مسیر را داشته باشیم باید مجدد آن را تعریف کنیم.

+

حالت گرافیکی

+

صفت‌های یک فضای گرافیکی مانند fillStyle, strokeStyle, lineWidth و lineJoin قسمتی از حالت گرافیکی فعلی هستند. فضای گرافیکی شامل دو متد save و restore است که می‌توانند برای انتقال حالت کنونی به مجموعه‌ی حالت‌ها یا از مجموعه‌ی حالت‌ها استفاده شوند.

+

یک نمونه‌ی پیچیده‌تر

+

در ادامه به نمونه‌ای پیچیده‌تر می‌پردازیم که شامل مسیرها، حالت، و همچنین ماتریس انتقال است. متدهای این فضا یعنی translate, scale و rotate برای انتقال ماتریس  به کار می‌روند که تمامی نقطه‌های ایجاد شده ابتدا توسط این ماتریس منتقل می‌شوند.

+

Example 3.

+
 <html>
+  <head>
+   <script type="application/javascript">
+ function drawBowtie(ctx, fillStyle) {
+
+   ctx.fillStyle = "rgba(200,200,200,0.3)";
+   ctx.fillRect(-30, -30, 60, 60);
+
+   ctx.fillStyle = fillStyle;
+   ctx.globalAlpha = 1.0;
+   ctx.beginPath();
+   ctx.moveTo(25, 25);
+   ctx.lineTo(-25, -25);
+   ctx.lineTo(25, -25);
+   ctx.lineTo(-25, 25);
+   ctx.closePath();
+   ctx.fill();
+ }
+
+ function dot(ctx) {
+   ctx.save();
+   ctx.fillStyle = "black";
+   ctx.fillRect(-2, -2, 4, 4);
+   ctx.restore();
+ }
+
+ function draw() {
+   var canvas = document.getElementById("canvas");
+   var ctx = canvas.getContext("2d");
+
+   // note that all other translates are relative to this
+   // one
+   ctx.translate(45, 45);
+
+   ctx.save();
+   //ctx.translate(0, 0); // unnecessary
+   drawBowtie(ctx, "red");
+   dot(ctx);
+   ctx.restore();
+
+   ctx.save();
+   ctx.translate(85, 0);
+   ctx.rotate(45 * Math.PI / 180);
+   drawBowtie(ctx, "green");
+   dot(ctx);
+   ctx.restore();
+
+   ctx.save();
+   ctx.translate(0, 85);
+   ctx.rotate(135 * Math.PI / 180);
+   drawBowtie(ctx, "blue");
+   dot(ctx);
+   ctx.restore();
+
+   ctx.save();
+   ctx.translate(85, 85);
+   ctx.rotate(90 * Math.PI / 180);
+   drawBowtie(ctx, "yellow");
+   dot(ctx);
+   ctx.restore();
+ }
+    </script>
+  </head>
+  <body onload="draw()">
+    <canvas id="canvas" width="300" height="300"></canvas>
+  </body>
+ </html>
+
+

قطعه کد بالا دو متد drawBowtie و dot را که هر کدام ۴ مرتبه فراخوانی شده‌اند، دربرمی‌گیرد. قبل از هر فراخوانی، از متدهای translate و rotate برای ایجاد ماتریس انتقال استفاده می‌شود که به ترتیب نقطه و پاپیون را مکان‌دهی می‌کنند. dot یک مستطیل کوچک به مرکز (0, 0) و drawBowtie یک پاپیون کوچک را با استفاده از مسیرها و رنگ مورد نظر به وجود می‌آورد.

+

هر چه عملیات ماتریس انباشته‌تر می‌شوند، متدهای save و restore برای ذخیره‌سازی و بازگرداندن حالت گرافیکی استفاده می‌شوند. چیزی که باید به یاد داشت این است که چرخش همیشه در مسیر فعلی شکل می‌گیرد یعنی ترتیب translate() rotate() translate() به یک شکل و ترتیب translate() translate() rotate() به شکلی دیگر منجر می‌شوند.

+

سازگاری با عنصر <canvas> اپل

+

در اکثر موارد، <canvas> با نمونه‌ی پیاده‌سازی شده‌ی اپل سازگاری دارد. اگرچه چند مورد هستند که باید به آن‌ها توجه کرد.

+

برچسب پایانی مورد نیاز است

+

در پیاده‌سازی سافاری از اپل، <canvas> عنصری است که مشابه <img> پیاده‌سازی شده است، یعنی به برچسب پایانی نیازی ندارد. اگرچه، برای این‌که <canvas> به صورت گسترده در وب استفاده شود، برخی امکانات برای محتوای بازگشتی بایستی فراهم شوند. از این رو، پیاده‌سازی موزیلا از این عنصر، نیازمند استفاده از برچسب پایانی است.

+

اگر به محتوای بازگشتی نیازی نباشد، یک نمونه‌ی ساده مانند <canvas id="foo" ...></canvas> با هر دو پیاده‌سازی سافاری و موزیلا سازگاری دارد، با این تفاوت که سافاری برچسب پایانی را در نظر نمی‌گیرد.

+

اگر محتوای بازگشتی مورد استفاده قرار گیرد، بایستی از برخی تکنیک‌های CSS برای ایجاد آن در سافاری استفاده کرد و همچنین از برخی تکنیک‌ها برای فهماندن این مطلب به IE!

+

ویژگی‌های دیگر

+

فراهم‌کردن محتوای وب در داخل Canvas

+
+ این ویژگی تنها با مجوزهای مرورگر Chrome قابل اعمال است و در صفحه‌های HTML معمولی استفاده نمی‌شود. علت آن را بدانید.
+

پیاده‌سازی موزیلا از canvas با استفاده از متد drawWindow گسترش یافته است. این متد تصویری از یک صفحه‌ی DOM را در داخل canvas رسم می‌کند. برای نمونه:

+

Mozilla's canvas is extended with the drawWindow() method. This method draws a snapshot of the contents of a DOM window into the canvas. For example,

+
ctx.drawWindow(window, 0, 0, 100, 200, "rgb(255,255,255)");
+
+

قطعه‌کد بالا محتوای پنجره‌ی فعلی را در مستطیلی با ابعاد ذکر شده به پیکسل نسبت به گوشه‌ی بالا و چپ پنچره در یک پیش‌زمینه‌ی سفید از بوم، رسم می‌کند. با مشخص کردن "rgba(255,255,255,0)" به عنوان رنگ، محتوا با پیش‌زمینه‌ی شفاف رسم می‌شود.

+

معمولا استفاده از رنگ پیش‌زمینه‌ای به جز سفید "rgb(255,255,255)" یا شفاف کار درستی نیست چرا که تمامی مرورگرها از این استاندارد برای نمایش صفحات وب استفاده می‌کنند.

+

با این روش، ممکن است بتوان یک IFRAME پنهان با محتوای دلخواه (برای نمونه متنی که با CSS سبک‌دهی شده باشد یا SVG) را در یک بوم رسم کرد، که به این صورت می‌توان آن را مقیاس‌دهی کرد یا چرخاند یا هر عمل دیگری که با انتقال‌های فعلی می‌توان انجام داد.

+

Ted Mielczarek با افزونه‌ی tab preview خود در chrome این امکان را فراهم می‌کند تا بتوان تصویرهای کوچک از وب‌سایت‌ها را مشاهده کرد، و کد آن نیز در دسترس است.

+
+ یادداشت: استفاده از canvas.drawWindow() در داخل رخداد onload سند عمل نمی‌کند. در فایرفاکس ۳.۵ به بعد، می‌توان با استفاده از رخداد MozAfterPaint این حالت را در زمان بارگذاری صفحه پیاده‌سازی کرد.
+

See also

+ +

{{ languages( { "fr": "fr/Dessiner_avec_canvas", "ja": "ja/Drawing_Graphics_with_Canvas", "pl": "pl/Rysowanie_grafik_za_pomoc\u0105_Canvas", "ko": "ko/Drawing_Graphics_with_Canvas" } ) }}

diff --git a/files/fa/web/api/htmlelement/innertext/index.html b/files/fa/web/api/htmlelement/innertext/index.html new file mode 100644 index 0000000000..98dd0eed8f --- /dev/null +++ b/files/fa/web/api/htmlelement/innertext/index.html @@ -0,0 +1,75 @@ +--- +title: Node.innerText +slug: Web/API/Node/innerText +translation_of: Web/API/HTMLElement/innerText +--- +
{{APIRef("DOM")}}
+ +

{{ Non-standard_header() }}

+ +

گزیده

+ +

Node.innerText یک ویژگی غیر استاندارد است که نشان دهنده محتوای متن یک node و زیر گروه های آن است به عنوان گیرنده متنی که کاربر می تواند با نشانگر موس از محتوا انتخاب  و آن را کپی نماید.

+ +

{{domxref("Node.textContent")}} یک جایگزین استاندارد تا حدی شبیه است، اگر چه تفاوت های مهمی بین این دو وجود دارد.

+ +

ویژگی ها

+ +

یک پیش نویس غیر رسمی از ویژگی ها در اینجا موجود است.

+ +

سازگاری با مرورگرها

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
پایه پشتیبانی4{{ CompatGeckoDesktop(45) }}69.6 (شاید پیش از این)3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
پایه پشتیبانی2.3 (شاید پیش از این){{ CompatGeckoMobile(45) }}10 (شاید پیش از این)124.1 (شاید پیش از این)
+
+ +

موارد مرتبط

+ + diff --git a/files/fa/web/api/node/innertext/index.html b/files/fa/web/api/node/innertext/index.html deleted file mode 100644 index 98dd0eed8f..0000000000 --- a/files/fa/web/api/node/innertext/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Node.innerText -slug: Web/API/Node/innerText -translation_of: Web/API/HTMLElement/innerText ---- -
{{APIRef("DOM")}}
- -

{{ Non-standard_header() }}

- -

گزیده

- -

Node.innerText یک ویژگی غیر استاندارد است که نشان دهنده محتوای متن یک node و زیر گروه های آن است به عنوان گیرنده متنی که کاربر می تواند با نشانگر موس از محتوا انتخاب  و آن را کپی نماید.

- -

{{domxref("Node.textContent")}} یک جایگزین استاندارد تا حدی شبیه است، اگر چه تفاوت های مهمی بین این دو وجود دارد.

- -

ویژگی ها

- -

یک پیش نویس غیر رسمی از ویژگی ها در اینجا موجود است.

- -

سازگاری با مرورگرها

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
پایه پشتیبانی4{{ CompatGeckoDesktop(45) }}69.6 (شاید پیش از این)3
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
پایه پشتیبانی2.3 (شاید پیش از این){{ CompatGeckoMobile(45) }}10 (شاید پیش از این)124.1 (شاید پیش از این)
-
- -

موارد مرتبط

- - diff --git a/files/fa/web/api/server-sent_events/index.html b/files/fa/web/api/server-sent_events/index.html new file mode 100644 index 0000000000..9b22801732 --- /dev/null +++ b/files/fa/web/api/server-sent_events/index.html @@ -0,0 +1,99 @@ +--- +title: Server-sent events +slug: Server-sent_events +tags: + - NeedsTranslation + - Server-sent events + - TopicStub +translation_of: Web/API/Server-sent_events +--- +

Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page.

+ + + + + + + +
+

Documentation

+
+
+ Using server-sent events
+
+ A tutorial guide to writing both server and client side part of a server-sent events app.
+
+ EventSource reference
+
+ A reference to the client-side EventSource API.
+
+

View All...

+
+

Tools

+ + + +
+

See also

+ +

Specification

+ +

Browser compatibility

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
EventSource support9{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}115
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
EventSource support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/fa/web/css/attribute_selectors/index.html b/files/fa/web/css/attribute_selectors/index.html new file mode 100644 index 0000000000..54cf34cd5d --- /dev/null +++ b/files/fa/web/css/attribute_selectors/index.html @@ -0,0 +1,182 @@ +--- +title: انتخابگر ویژگی +slug: Web/CSS/انتخابگرـویژگی +translation_of: Web/CSS/Attribute_selectors +--- +
{{CSSRef}}
+ +

انتخابگر ویژگی بر اساس وجود ویژگی یا مقدار ویژگی انتخاب می‌کند.

+ +
/* را داشته باشند title که ویژگی <a> عنصرهای */
+a[title] {
+  color: purple;
+}
+
+/* باشد "https://example.org" آن برابر با  href که ویژگی  <a> عنصرهای */
+a[href="https://example.org"] {
+  color: green;
+}
+
+/* باشد "example" آن در بردارنده‌ی href که ویژگی <a> عنصرهای */
+a[href*="example"] {
+  font-size: 2em;
+}
+
+/* به پایان رسیده باشد ".org" آن با href که ویژگی <a> عنصرهای */
+a[href$=".org"] {
+  font-style: italic;
+}
+ +
+
[attr]
+
Represents elements with an attribute name of attr.
+
[attr=value]
+
Represents elements with an attribute name of attr whose value is exactly value.
+
[attr~=value]
+
Represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.
+
[attr|=value]
+
Represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, - (U+002D). It is often used for language subcode matches.
+
[attr^=value]
+
Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.
+
[attr$=value]
+
Represents elements with an attribute name of attr whose value is suffixed (followed) by value.
+
[attr*=value]
+
Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
+
[attr operator value i]
+
Adding an i (or I) before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range).
+
+ +

Examples

+ + + +

CSS

+ +
a {
+  color: blue;
+}
+
+/* Internal links, beginning with "#" */
+a[href^="#"] {
+  background-color: gold;
+}
+
+/* Links with "example" anywhere in the URL */
+a[href*="example"] {
+  background-color: silver;
+}
+
+/* Links with "insensitive" anywhere in the URL,
+   regardless of capitalization */
+a[href*="insensitive" i] {
+  color: cyan;
+}
+
+/* Links that end in ".org" */
+a[href$=".org"] {
+  color: red;
+}
+
+ +

HTML

+ +
<ul>
+  <li><a href="#internal">Internal link</a></li>
+  <li><a href="http://example.com">Example link</a></li>
+  <li><a href="#InSensitive">Insensitive internal link</a></li>
+  <li><a href="http://example.org">Example org link</a></li>
+</ul>
+ +

Result

+ +

{{EmbedLiveSample('Links')}}

+ +

Languages

+ +

CSS

+ +
/* All divs with a `lang` attribute are bold. */
+div[lang] {
+  font-weight: bold;
+}
+
+/* All divs in US English are blue. */
+div[lang~="en-us"] {
+  color: blue;
+}
+
+/* All divs in Portuguese are green. */
+div[lang="pt"] {
+  color: green;
+}
+
+/* All divs in Chinese are red, whether
+   simplified (zh-CN) or traditional (zh-TW). */
+div[lang|="zh"] {
+  color: red;
+}
+
+/* All divs with a Traditional Chinese
+   `data-lang` are purple. */
+/* Note: You could also use hyphenated attributes
+   without double quotes */
+div[data-lang="zh-TW"] {
+  color: purple;
+}
+
+ +

HTML

+ +
<div lang="en-us en-gb en-au en-nz">Hello World!</div>
+<div lang="pt">Olá Mundo!</div>
+<div lang="zh-CN">世界您好!</div>
+<div lang="zh-TW">世界您好!</div>
+<div data-lang="zh-TW">?世界您好!</div>
+
+ +

Result

+ +

{{EmbedLiveSample('Languages')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS4 Selectors')}}Adds modifier for ASCII case-insensitive attribute value selection
{{SpecName('CSS3 Selectors', '#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS3 Selectors')}} 
{{SpecName('CSS2.1', 'selector.html#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS2.1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.selectors.attribute")}}

+ +

See also

+ + diff --git a/files/fa/web/css/media_queries/using_media_queries/index.html b/files/fa/web/css/media_queries/using_media_queries/index.html new file mode 100644 index 0000000000..286a3e8ba2 --- /dev/null +++ b/files/fa/web/css/media_queries/using_media_queries/index.html @@ -0,0 +1,331 @@ +--- +title: ابزار تست رسانه پاسخگو +slug: Web/CSS/Media_Queries/ابزار-تست-رسانه-پاسخگو +translation_of: Web/CSS/Media_Queries/Using_media_queries +--- +
{{cssref}}
+ +

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

+ +

هدف قرار دادن انواع رسانه ها

+ +

انواع رسانه ها دسته کلی یک دستگاه مشخص را توصیف می کنند. اگر چه وبسایت ها معمولا با صفحه نمایش طراحی شده اند، ممکن است بخواهید سبکهایی را ایجاد کنید که دستگاه هایی خاص مانند چاپگرها  یا  صفحه نمایش مبتنی بر صدا را هدف قرار میدهند. به عنوان مثال، این کد CSS  چاپگر ها را هدف قرار میدهد :

+ +
@media print { ... }
+ +

همچنین می توانید به راحتی چندین دستگاه را هدف قرار دهید. به عنوان مثال، دستور@media با استفاده از دو ابزار رسانه پاسخگو، صفحه نمایش و همینطور چاپگر را هدف قرار میدهد:

+ +
@media screen, print { ... }
+ +

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

+ +

Targeting media features

+ +

Media features describe the specific characteristics of a given {{glossary("user agent")}}, output device, or environment. For instance, you can apply specific styles to widescreen monitors, computers that use mice, or to devices that are being used in low-light conditions. This example applies styles when the user's primary input mechanism (such as a mouse) can hover over elements:

+ +
@media (hover: hover) { ... }
+ +

Many media features are range features, which means they can be prefixed with "min-" or "max-" to express "minimum condition" or "maximum condition" constraints. For example, this CSS will apply styles only if your browser's {{glossary("viewport")}} is equal to or narrower than 12,450 pixels:

+ +
@media (max-width: 12450px) { ... }
+ +

If you create a media feature query without specifying a value, the nested styles will be used as long as the feature's value is non-zero. For example, this CSS will apply to any device with a color screen:

+ +
@media (color) { ... }
+ +

If a feature doesn't apply to the device on which the browser is running, expressions involving that media feature are always false. For example, the styles nested inside the following query will never be used, because no speech-only device has a screen aspect ratio:

+ +
@media speech and (aspect-ratio: 11/5) { ... }
+ +

For more media feature examples, please see the reference page for each specific feature.

+ +

Creating complex media queries

+ +

Sometimes you may want to create a media query that depends on multiple conditions. This is where the logical operators come in: not, and, and only. Furthermore, you can combine multiple media queries into a comma-separated list; this allows you to apply the same styles in different situations.

+ +

In the previous example, we've already seen the and operator used to group a media type with a media feature. The and operator can also combine multiple media features into a single media query. The not operator, meanwhile, negates a media query, basically reversing its normal meaning. The only operator prevents older browsers from applying the styles.

+ +
+

Note: In most cases, the all media type is used by default when no other type is specified. However, if you use the not or only operators, you must explicitly specify a media type.

+
+ +

and

+ +

The and keyword combines a media feature with a media type or other media features. This example combines two media features to restrict styles to landscape-oriented devices with a width of at least 30 ems:

+ +
@media (min-width: 30em) and (orientation: landscape) { ... }
+ +

To limit the styles to devices with a screen, you can chain the media features to the screen media type:

+ +
@media screen and (min-width: 30em) and (orientation: landscape) { ...  }
+ +

comma-separated lists

+ +

You can use a comma-separated list to apply styles when the user's device matches any one of various media types, features, or states. For instance, the following rule will apply its styles if the user's device has either a minimum height of 680 pixels or is a screen device in portrait mode:

+ +
@media (min-height: 680px), screen and (orientation: portrait) { ... }
+ +

Taking the above example, if the user had a printer with a page height of 800 pixels, the media statement would return true because the first query would apply. Likewise, if the user were on a smartphone in portrait mode with a viewport height of 480 pixels, the second query would apply and the media statement would still return true.

+ +

not

+ +

The not keyword inverts the meaning of an entire media query. It will only negate the specific media query it is applied to. (Thus, it will not apply to every media query in a comma-separated list of media queries.) The not keyword can't be used to negate an individual feature query, only an entire media query. The not is evaluated last in the following query:

+ +
@media not all and (monochrome) { ... }
+
+ +

... so that the above query is evaluated like this:

+ +
@media not (all and (monochrome)) { ... }
+
+ +

... rather than like this:

+ +
@media (not all) and (monochrome) { ... }
+ +

As another example, the following media query:

+ +
@media not screen and (color), print and (color) { ... }
+
+ +

... is evaluated like this:

+ +
@media (not (screen and (color))), print and (color) { ... }
+ +

only

+ +

The only keyword prevents older browsers that do not support media queries with media features from applying the given styles. It has no effect on modern browsers.

+ +
<link rel="stylesheet" media="only screen and (color)" href="modern-styles.css" />
+
+ +

Mozilla-specific media features

+ +

Mozilla offers several Gecko-specific media features. Some of these may be proposed as official media features in the future.

+ + + +

WebKit-specific media features

+ +

For WebKit-specific media features, please see the reference page for each specific feature.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("21")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9.0")}}{{CompatOpera("9")}}{{CompatSafari("4")}}
grid{{CompatUnknown}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
resolution{{CompatChrome("29")}}{{CompatGeckoDesktop("1.9.1")}} [2]
+ {{CompatGeckoDesktop("8.0")}} [3]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scan{{CompatUnknown}}{{CompatNo}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-min-device-pixel-ratio, -webkit-max-device-pixel-ratio{{CompatVersionUnknown}}{{CompatNo}}[7]{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
-webkit-transform-3d{{CompatVersionUnknown}}[5]{{CompatGeckoDesktop("49")}}[6]{{CompatUnknown}}{{CompatVersionUnknown}}[5]{{CompatSafari("1.0")}}[5]
-webkit-transform-2d{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}[5]{{CompatSafari("1.0")}}[5]
-webkit-transition{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}[5]{{CompatSafari("1.0")}}[5]
display-mode{{CompatUnknown}}{{CompatGeckoDesktop("47")}}[8]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
grid{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
resolution{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scan{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-min-device-pixel-ratio, -webkit-max-device-pixel-ratio{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-transform-3d{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-transform-2d{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-transition{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
display-mode{{CompatUnknown}}{{CompatGeckoMobile(47)}}[8]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] grid media type is not supported.

+ +

[2] Supports {{cssxref("<integer>")}} values only.

+ +

[3] Supports {{cssxref("<number>")}} values, as per the spec.

+ +

[4] tv media type is not supported.

+ +

[5] See {{WebKitBug(22494)}}.

+ +

[6] Implemented for Web compatibility reasons in Gecko 46.0 {{geckoRelease("46.0")}} behind the preference layout.css.prefixes.webkit defaulting to false. See {{bug(1239799)}}. Since Gecko 49.0 {{geckoRelease("49")}} layout.css.prefixes.webkit defaults to true.

+ +

[7] Implemented as aliases for min--moz-device-pixel-ratio and max--moz-device-pixel-ratio for Web compatibility reasons in Gecko 45.0 {{geckoRelease("45.0")}} (see {{bug(1176968)}}) behind the preferences layout.css.prefixes.webkit and layout.css.prefixes.device-pixel-ratio-webkit, defaulting to false. Since Gecko 49.0 {{geckoRelease("49")}} layout.css.prefixes.webkit defaults to true.

+ +

[8] Only the fullscreen and browser values of display-mode were supported in 47. minimal-ui and standalone were added in Firefox 57.

+ +

See also

+ + diff --git "a/files/fa/web/css/media_queries/\330\247\330\250\330\262\330\247\330\261-\330\252\330\263\330\252-\330\261\330\263\330\247\331\206\331\207-\331\276\330\247\330\263\330\256\332\257\331\210/index.html" "b/files/fa/web/css/media_queries/\330\247\330\250\330\262\330\247\330\261-\330\252\330\263\330\252-\330\261\330\263\330\247\331\206\331\207-\331\276\330\247\330\263\330\256\332\257\331\210/index.html" deleted file mode 100644 index 286a3e8ba2..0000000000 --- "a/files/fa/web/css/media_queries/\330\247\330\250\330\262\330\247\330\261-\330\252\330\263\330\252-\330\261\330\263\330\247\331\206\331\207-\331\276\330\247\330\263\330\256\332\257\331\210/index.html" +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: ابزار تست رسانه پاسخگو -slug: Web/CSS/Media_Queries/ابزار-تست-رسانه-پاسخگو -translation_of: Web/CSS/Media_Queries/Using_media_queries ---- -
{{cssref}}
- -

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

- -

هدف قرار دادن انواع رسانه ها

- -

انواع رسانه ها دسته کلی یک دستگاه مشخص را توصیف می کنند. اگر چه وبسایت ها معمولا با صفحه نمایش طراحی شده اند، ممکن است بخواهید سبکهایی را ایجاد کنید که دستگاه هایی خاص مانند چاپگرها  یا  صفحه نمایش مبتنی بر صدا را هدف قرار میدهند. به عنوان مثال، این کد CSS  چاپگر ها را هدف قرار میدهد :

- -
@media print { ... }
- -

همچنین می توانید به راحتی چندین دستگاه را هدف قرار دهید. به عنوان مثال، دستور@media با استفاده از دو ابزار رسانه پاسخگو، صفحه نمایش و همینطور چاپگر را هدف قرار میدهد:

- -
@media screen, print { ... }
- -

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

- -

Targeting media features

- -

Media features describe the specific characteristics of a given {{glossary("user agent")}}, output device, or environment. For instance, you can apply specific styles to widescreen monitors, computers that use mice, or to devices that are being used in low-light conditions. This example applies styles when the user's primary input mechanism (such as a mouse) can hover over elements:

- -
@media (hover: hover) { ... }
- -

Many media features are range features, which means they can be prefixed with "min-" or "max-" to express "minimum condition" or "maximum condition" constraints. For example, this CSS will apply styles only if your browser's {{glossary("viewport")}} is equal to or narrower than 12,450 pixels:

- -
@media (max-width: 12450px) { ... }
- -

If you create a media feature query without specifying a value, the nested styles will be used as long as the feature's value is non-zero. For example, this CSS will apply to any device with a color screen:

- -
@media (color) { ... }
- -

If a feature doesn't apply to the device on which the browser is running, expressions involving that media feature are always false. For example, the styles nested inside the following query will never be used, because no speech-only device has a screen aspect ratio:

- -
@media speech and (aspect-ratio: 11/5) { ... }
- -

For more media feature examples, please see the reference page for each specific feature.

- -

Creating complex media queries

- -

Sometimes you may want to create a media query that depends on multiple conditions. This is where the logical operators come in: not, and, and only. Furthermore, you can combine multiple media queries into a comma-separated list; this allows you to apply the same styles in different situations.

- -

In the previous example, we've already seen the and operator used to group a media type with a media feature. The and operator can also combine multiple media features into a single media query. The not operator, meanwhile, negates a media query, basically reversing its normal meaning. The only operator prevents older browsers from applying the styles.

- -
-

Note: In most cases, the all media type is used by default when no other type is specified. However, if you use the not or only operators, you must explicitly specify a media type.

-
- -

and

- -

The and keyword combines a media feature with a media type or other media features. This example combines two media features to restrict styles to landscape-oriented devices with a width of at least 30 ems:

- -
@media (min-width: 30em) and (orientation: landscape) { ... }
- -

To limit the styles to devices with a screen, you can chain the media features to the screen media type:

- -
@media screen and (min-width: 30em) and (orientation: landscape) { ...  }
- -

comma-separated lists

- -

You can use a comma-separated list to apply styles when the user's device matches any one of various media types, features, or states. For instance, the following rule will apply its styles if the user's device has either a minimum height of 680 pixels or is a screen device in portrait mode:

- -
@media (min-height: 680px), screen and (orientation: portrait) { ... }
- -

Taking the above example, if the user had a printer with a page height of 800 pixels, the media statement would return true because the first query would apply. Likewise, if the user were on a smartphone in portrait mode with a viewport height of 480 pixels, the second query would apply and the media statement would still return true.

- -

not

- -

The not keyword inverts the meaning of an entire media query. It will only negate the specific media query it is applied to. (Thus, it will not apply to every media query in a comma-separated list of media queries.) The not keyword can't be used to negate an individual feature query, only an entire media query. The not is evaluated last in the following query:

- -
@media not all and (monochrome) { ... }
-
- -

... so that the above query is evaluated like this:

- -
@media not (all and (monochrome)) { ... }
-
- -

... rather than like this:

- -
@media (not all) and (monochrome) { ... }
- -

As another example, the following media query:

- -
@media not screen and (color), print and (color) { ... }
-
- -

... is evaluated like this:

- -
@media (not (screen and (color))), print and (color) { ... }
- -

only

- -

The only keyword prevents older browsers that do not support media queries with media features from applying the given styles. It has no effect on modern browsers.

- -
<link rel="stylesheet" media="only screen and (color)" href="modern-styles.css" />
-
- -

Mozilla-specific media features

- -

Mozilla offers several Gecko-specific media features. Some of these may be proposed as official media features in the future.

- - - -

WebKit-specific media features

- -

For WebKit-specific media features, please see the reference page for each specific feature.

- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("21")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9.0")}}{{CompatOpera("9")}}{{CompatSafari("4")}}
grid{{CompatUnknown}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
resolution{{CompatChrome("29")}}{{CompatGeckoDesktop("1.9.1")}} [2]
- {{CompatGeckoDesktop("8.0")}} [3]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scan{{CompatUnknown}}{{CompatNo}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-min-device-pixel-ratio, -webkit-max-device-pixel-ratio{{CompatVersionUnknown}}{{CompatNo}}[7]{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
-webkit-transform-3d{{CompatVersionUnknown}}[5]{{CompatGeckoDesktop("49")}}[6]{{CompatUnknown}}{{CompatVersionUnknown}}[5]{{CompatSafari("1.0")}}[5]
-webkit-transform-2d{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}[5]{{CompatSafari("1.0")}}[5]
-webkit-transition{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}[5]{{CompatSafari("1.0")}}[5]
display-mode{{CompatUnknown}}{{CompatGeckoDesktop("47")}}[8]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
grid{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
resolution{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scan{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-min-device-pixel-ratio, -webkit-max-device-pixel-ratio{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-transform-3d{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-transform-2d{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-webkit-transition{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
display-mode{{CompatUnknown}}{{CompatGeckoMobile(47)}}[8]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] grid media type is not supported.

- -

[2] Supports {{cssxref("<integer>")}} values only.

- -

[3] Supports {{cssxref("<number>")}} values, as per the spec.

- -

[4] tv media type is not supported.

- -

[5] See {{WebKitBug(22494)}}.

- -

[6] Implemented for Web compatibility reasons in Gecko 46.0 {{geckoRelease("46.0")}} behind the preference layout.css.prefixes.webkit defaulting to false. See {{bug(1239799)}}. Since Gecko 49.0 {{geckoRelease("49")}} layout.css.prefixes.webkit defaults to true.

- -

[7] Implemented as aliases for min--moz-device-pixel-ratio and max--moz-device-pixel-ratio for Web compatibility reasons in Gecko 45.0 {{geckoRelease("45.0")}} (see {{bug(1176968)}}) behind the preferences layout.css.prefixes.webkit and layout.css.prefixes.device-pixel-ratio-webkit, defaulting to false. Since Gecko 49.0 {{geckoRelease("49")}} layout.css.prefixes.webkit defaults to true.

- -

[8] Only the fullscreen and browser values of display-mode were supported in 47. minimal-ui and standalone were added in Firefox 57.

- -

See also

- - diff --git a/files/fa/web/css/type_selectors/index.html b/files/fa/web/css/type_selectors/index.html new file mode 100644 index 0000000000..5a4b5e4c89 --- /dev/null +++ b/files/fa/web/css/type_selectors/index.html @@ -0,0 +1,78 @@ +--- +title: انتخابگر نوع +slug: Web/CSS/انتخابگرـنوع +translation_of: Web/CSS/Type_selectors +--- +
{{CSSRef}}
+ +

انتخابگر نوع با نوع عنصر انتخاب می‌کند. به عبارت دیگر این انتخابگر به وسیله نوع عنصر، تمام عنصرهای تطابق داده شده را انتخاب می‌کند.

+ +
/* را انتخاب می‌کند <a> همه عنصرهای */
+a {
+  color: red;
+}
+ +

Syntax

+ +
element { style properties }
+
+ +

Example

+ +

CSS

+ +
span {
+  background-color: skyblue;
+}
+
+ +

HTML

+ +
<span>Here's a span with some text.</span>
+<p>Here's a p with some text.</p>
+<span>Here's a span with more text.</span>
+
+ +

Result

+ +

{{EmbedLiveSample('Example', '100%', 150)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#type-selectors', 'Type (tag name) selector')}}{{Spec2('CSS4 Selectors')}}No changes
{{SpecName('CSS3 Selectors', '#type-selectors', 'type selectors')}}{{Spec2('CSS3 Selectors')}}No changes
{{SpecName('CSS2.1', 'selector.html#type-selectors', 'type selectors')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#basic-concepts', 'type selectors')}}{{Spec2('CSS1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.selectors.type")}}

diff --git a/files/fa/web/css/zoom/index.html b/files/fa/web/css/zoom/index.html new file mode 100644 index 0000000000..e664b6b4cc --- /dev/null +++ b/files/fa/web/css/zoom/index.html @@ -0,0 +1,134 @@ +--- +title: بزرگنمایی +slug: Web/CSS/بزرگنمایی +translation_of: Web/CSS/zoom +--- +
{{CSSRef}}{{Non-standard_header}}
+ +

The non-standard zoom CSS property can be used to control the magnification level of an element. {{cssxref("transform-function/scale", "transform: scale()")}} should be used instead of this property, if possible. However, unlike CSS Transforms, zoom affects the layout size of the element.

+ +
/* Keyword values */
+zoom: normal;
+zoom: reset;
+
+/* <percentage> values */
+zoom: 50%;
+zoom: 200%;
+
+/* <number> values */
+zoom: 1.1;
+zoom: 0.7;
+
+/* Global values */
+zoom: inherit;
+zoom: initial;
+zoom: unset;
+ +

{{cssinfo}}

+ +

Syntax

+ +

Values

+ +
+
normal
+
Render this element at its normal size.
+
reset {{non-standard_inline}}
+
Do not (de)magnify this element if the user applies non-pinch-based zooming (e.g. by pressing Ctrl-- or Ctrl++ keyboard shortcuts) to the document. Only supported by WebKit (and possibly Blink).
+
{{cssxref("<percentage>")}}
+
Zoom factor. 100% is equivalent to normal. Values larger than 100% zoom in. Values smaller than 100% zoom out.
+
{{cssxref("<number>")}}
+
Zoom factor. Equivalent to the corresponding percentage (1.0 = 100% = normal). Values larger than 1.0 zoom in. Values smaller than 1.0 zoom out.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

First example

+ +

HTML

+ +
<p class="small">Small</p>
+<p class="normal">Normal</p>
+<p class="big">Big</p>
+ +

CSS

+ +
p.small {
+  zoom: 75%;
+}
+p.normal {
+  zoom: normal;
+}
+p.big {
+  zoom: 2.5;
+}
+p {
+  display: inline-block;
+}
+p:hover {
+  zoom: reset;
+}
+
+ +

Result

+ +

{{EmbedLiveSample('First_example')}}

+ +

Second example

+ +

HTML

+ +
<div id="a" class="circle"></div>
+<div id="b" class="circle"></div>
+<div id="c" class="circle"></div>
+ +

CSS

+ +
div.circle {
+  width: 25px;
+  height: 25px;
+  border-radius: 100%;
+  text-align: center;
+  vertical-align: middle;
+  display: inline-block;
+  zoom: 1.5;
+}
+div#a {
+  background-color: gold;
+  zoom: normal;
+}
+div#b {
+  background-color: green;
+  zoom: 200%;
+}
+div#c {
+  background-color: blue;
+  zoom: 2.9;
+}
+
+ +

Result

+ +

{{EmbedLiveSample('Second_example')}}

+ +

Specifications

+ +

This property is nonstandard and originated in Internet Explorer. Apple has a description in the Safari CSS Reference. Rossen Atanassov of Microsoft has an unofficial draft specification proposal on GitHub.

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.zoom")}}

+ +

See also

+ + diff --git "a/files/fa/web/css/\330\247\331\206\330\252\330\256\330\247\330\250\332\257\330\261\331\200\331\206\331\210\330\271/index.html" "b/files/fa/web/css/\330\247\331\206\330\252\330\256\330\247\330\250\332\257\330\261\331\200\331\206\331\210\330\271/index.html" deleted file mode 100644 index 5a4b5e4c89..0000000000 --- "a/files/fa/web/css/\330\247\331\206\330\252\330\256\330\247\330\250\332\257\330\261\331\200\331\206\331\210\330\271/index.html" +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: انتخابگر نوع -slug: Web/CSS/انتخابگرـنوع -translation_of: Web/CSS/Type_selectors ---- -
{{CSSRef}}
- -

انتخابگر نوع با نوع عنصر انتخاب می‌کند. به عبارت دیگر این انتخابگر به وسیله نوع عنصر، تمام عنصرهای تطابق داده شده را انتخاب می‌کند.

- -
/* را انتخاب می‌کند <a> همه عنصرهای */
-a {
-  color: red;
-}
- -

Syntax

- -
element { style properties }
-
- -

Example

- -

CSS

- -
span {
-  background-color: skyblue;
-}
-
- -

HTML

- -
<span>Here's a span with some text.</span>
-<p>Here's a p with some text.</p>
-<span>Here's a span with more text.</span>
-
- -

Result

- -

{{EmbedLiveSample('Example', '100%', 150)}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#type-selectors', 'Type (tag name) selector')}}{{Spec2('CSS4 Selectors')}}No changes
{{SpecName('CSS3 Selectors', '#type-selectors', 'type selectors')}}{{Spec2('CSS3 Selectors')}}No changes
{{SpecName('CSS2.1', 'selector.html#type-selectors', 'type selectors')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#basic-concepts', 'type selectors')}}{{Spec2('CSS1')}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("css.selectors.type")}}

diff --git "a/files/fa/web/css/\330\247\331\206\330\252\330\256\330\247\330\250\332\257\330\261\331\200\331\210\333\214\332\230\332\257\333\214/index.html" "b/files/fa/web/css/\330\247\331\206\330\252\330\256\330\247\330\250\332\257\330\261\331\200\331\210\333\214\332\230\332\257\333\214/index.html" deleted file mode 100644 index 54cf34cd5d..0000000000 --- "a/files/fa/web/css/\330\247\331\206\330\252\330\256\330\247\330\250\332\257\330\261\331\200\331\210\333\214\332\230\332\257\333\214/index.html" +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: انتخابگر ویژگی -slug: Web/CSS/انتخابگرـویژگی -translation_of: Web/CSS/Attribute_selectors ---- -
{{CSSRef}}
- -

انتخابگر ویژگی بر اساس وجود ویژگی یا مقدار ویژگی انتخاب می‌کند.

- -
/* را داشته باشند title که ویژگی <a> عنصرهای */
-a[title] {
-  color: purple;
-}
-
-/* باشد "https://example.org" آن برابر با  href که ویژگی  <a> عنصرهای */
-a[href="https://example.org"] {
-  color: green;
-}
-
-/* باشد "example" آن در بردارنده‌ی href که ویژگی <a> عنصرهای */
-a[href*="example"] {
-  font-size: 2em;
-}
-
-/* به پایان رسیده باشد ".org" آن با href که ویژگی <a> عنصرهای */
-a[href$=".org"] {
-  font-style: italic;
-}
- -
-
[attr]
-
Represents elements with an attribute name of attr.
-
[attr=value]
-
Represents elements with an attribute name of attr whose value is exactly value.
-
[attr~=value]
-
Represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.
-
[attr|=value]
-
Represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, - (U+002D). It is often used for language subcode matches.
-
[attr^=value]
-
Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.
-
[attr$=value]
-
Represents elements with an attribute name of attr whose value is suffixed (followed) by value.
-
[attr*=value]
-
Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
-
[attr operator value i]
-
Adding an i (or I) before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range).
-
- -

Examples

- - - -

CSS

- -
a {
-  color: blue;
-}
-
-/* Internal links, beginning with "#" */
-a[href^="#"] {
-  background-color: gold;
-}
-
-/* Links with "example" anywhere in the URL */
-a[href*="example"] {
-  background-color: silver;
-}
-
-/* Links with "insensitive" anywhere in the URL,
-   regardless of capitalization */
-a[href*="insensitive" i] {
-  color: cyan;
-}
-
-/* Links that end in ".org" */
-a[href$=".org"] {
-  color: red;
-}
-
- -

HTML

- -
<ul>
-  <li><a href="#internal">Internal link</a></li>
-  <li><a href="http://example.com">Example link</a></li>
-  <li><a href="#InSensitive">Insensitive internal link</a></li>
-  <li><a href="http://example.org">Example org link</a></li>
-</ul>
- -

Result

- -

{{EmbedLiveSample('Links')}}

- -

Languages

- -

CSS

- -
/* All divs with a `lang` attribute are bold. */
-div[lang] {
-  font-weight: bold;
-}
-
-/* All divs in US English are blue. */
-div[lang~="en-us"] {
-  color: blue;
-}
-
-/* All divs in Portuguese are green. */
-div[lang="pt"] {
-  color: green;
-}
-
-/* All divs in Chinese are red, whether
-   simplified (zh-CN) or traditional (zh-TW). */
-div[lang|="zh"] {
-  color: red;
-}
-
-/* All divs with a Traditional Chinese
-   `data-lang` are purple. */
-/* Note: You could also use hyphenated attributes
-   without double quotes */
-div[data-lang="zh-TW"] {
-  color: purple;
-}
-
- -

HTML

- -
<div lang="en-us en-gb en-au en-nz">Hello World!</div>
-<div lang="pt">Olá Mundo!</div>
-<div lang="zh-CN">世界您好!</div>
-<div lang="zh-TW">世界您好!</div>
-<div data-lang="zh-TW">?世界您好!</div>
-
- -

Result

- -

{{EmbedLiveSample('Languages')}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS4 Selectors')}}Adds modifier for ASCII case-insensitive attribute value selection
{{SpecName('CSS3 Selectors', '#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS3 Selectors')}} 
{{SpecName('CSS2.1', 'selector.html#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS2.1')}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("css.selectors.attribute")}}

- -

See also

- - diff --git "a/files/fa/web/css/\330\250\330\262\330\261\332\257\331\206\331\205\330\247\333\214\333\214/index.html" "b/files/fa/web/css/\330\250\330\262\330\261\332\257\331\206\331\205\330\247\333\214\333\214/index.html" deleted file mode 100644 index e664b6b4cc..0000000000 --- "a/files/fa/web/css/\330\250\330\262\330\261\332\257\331\206\331\205\330\247\333\214\333\214/index.html" +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: بزرگنمایی -slug: Web/CSS/بزرگنمایی -translation_of: Web/CSS/zoom ---- -
{{CSSRef}}{{Non-standard_header}}
- -

The non-standard zoom CSS property can be used to control the magnification level of an element. {{cssxref("transform-function/scale", "transform: scale()")}} should be used instead of this property, if possible. However, unlike CSS Transforms, zoom affects the layout size of the element.

- -
/* Keyword values */
-zoom: normal;
-zoom: reset;
-
-/* <percentage> values */
-zoom: 50%;
-zoom: 200%;
-
-/* <number> values */
-zoom: 1.1;
-zoom: 0.7;
-
-/* Global values */
-zoom: inherit;
-zoom: initial;
-zoom: unset;
- -

{{cssinfo}}

- -

Syntax

- -

Values

- -
-
normal
-
Render this element at its normal size.
-
reset {{non-standard_inline}}
-
Do not (de)magnify this element if the user applies non-pinch-based zooming (e.g. by pressing Ctrl-- or Ctrl++ keyboard shortcuts) to the document. Only supported by WebKit (and possibly Blink).
-
{{cssxref("<percentage>")}}
-
Zoom factor. 100% is equivalent to normal. Values larger than 100% zoom in. Values smaller than 100% zoom out.
-
{{cssxref("<number>")}}
-
Zoom factor. Equivalent to the corresponding percentage (1.0 = 100% = normal). Values larger than 1.0 zoom in. Values smaller than 1.0 zoom out.
-
- -

Formal syntax

- -
{{csssyntax}}
- -

Examples

- -

First example

- -

HTML

- -
<p class="small">Small</p>
-<p class="normal">Normal</p>
-<p class="big">Big</p>
- -

CSS

- -
p.small {
-  zoom: 75%;
-}
-p.normal {
-  zoom: normal;
-}
-p.big {
-  zoom: 2.5;
-}
-p {
-  display: inline-block;
-}
-p:hover {
-  zoom: reset;
-}
-
- -

Result

- -

{{EmbedLiveSample('First_example')}}

- -

Second example

- -

HTML

- -
<div id="a" class="circle"></div>
-<div id="b" class="circle"></div>
-<div id="c" class="circle"></div>
- -

CSS

- -
div.circle {
-  width: 25px;
-  height: 25px;
-  border-radius: 100%;
-  text-align: center;
-  vertical-align: middle;
-  display: inline-block;
-  zoom: 1.5;
-}
-div#a {
-  background-color: gold;
-  zoom: normal;
-}
-div#b {
-  background-color: green;
-  zoom: 200%;
-}
-div#c {
-  background-color: blue;
-  zoom: 2.9;
-}
-
- -

Result

- -

{{EmbedLiveSample('Second_example')}}

- -

Specifications

- -

This property is nonstandard and originated in Internet Explorer. Apple has a description in the Safari CSS Reference. Rossen Atanassov of Microsoft has an unofficial draft specification proposal on GitHub.

- -

Browser compatibility

- - - -

{{Compat("css.properties.zoom")}}

- -

See also

- - diff --git a/files/fa/web/guide/html/html5/index.html b/files/fa/web/guide/html/html5/index.html new file mode 100644 index 0000000000..f2ae6b581b --- /dev/null +++ b/files/fa/web/guide/html/html5/index.html @@ -0,0 +1,155 @@ +--- +title: HTML5 +slug: HTML/HTML5 +translation_of: Web/Guide/HTML/HTML5 +--- +

HTML5 آخرین نسخه از مجموعه استانداردهای HTML است، که نشان‌دهنده‌ی دو مفهوم متفاوت است:

+ + + +

این صفحه به منابع متفاوتی از فناوری‌های HTML5 پیوند خورده است، دسته‌بندی شده در گروه‌های مختلف، که هر گروه دربرگیرنده‌ی فعالیتی متفاوت است: semantics (عنصر‌های معناگرا)، که در توضیح هر چه بیشتر و دقیق‌تر محتوا نقش دارند، connectivity (اتصال)، که روش‌های جدیدی برای برقراری ارتباط با سرور معرفی می‌کند، offline & storage (ذخیره‌سازی آفلاین)، که وب‌سایت را برای ذخیره‌ی داده‌های آفلاین و عملکرد بهتر زمانی که مرورگر کاربر در حالت آفلاین قرار دارد بهینه می‌کند، multimedia (محتوای چندرسانه‌ای)، که صوت و تصویر را به عنوان شهروند درجه یک وب معرفی می‌کند، 3D، Graphics & Effects (سه‌بعدی، گرافیک و جلوه‌های تصویری)، که به ارایه‌ی جلوه‌های تصویری پیچیده‌تر منجر می‌شود، performance & integration (عملکرد و جامعیت)، که وب‌سایتی سریع‌تر و در عین حال منطبق‌تر با رایانه‌ی کاربر می‌سازد، device access (دسترسی از طریق سایر دستگاه‌ها)، که اجازه‌ی استفاده‌ی دستگاه‌های ورودی/خروجی بیشتری را می‌دهد، و styling (سبک‌دهی)، که دست توسعه‌دهندگان در ایجاد قالب‌های پیچیده‌تر را باز می‌کند.

+ +
+
+

Semantics (عنصرهای معناگرا)

+ +
+
بخش‌های مختلف صفحه در HTML5
+
نگاهی به عنصرهای بخش‌بندی صفحه در HTML5:
+
{{ HTMLElement("section") }}, {{ HTMLElement("article") }}, {{ HTMLElement("nav") }}, {{ HTMLElement("header") }}, {{ HTMLElement("footer") }}, {{ HTMLElement("aside") }} و {{ HTMLElement("hgroup") }}.
+
استفاده از audio و vedio در HTML5
+
عنصرهای {{ HTMLElement("audio") }} و {{ HTMLElement("video") }} با قرارگرفتن در صفحه، اجازه‌ی تغییراتی جدید در نحوه‌ی اجرای محتوای چندرسانه‌ای را می‌دهند.
+
فرم‌ها در HTML5
+
نگاهی به بهبودهای ایجادشده در فرم‌های وب، constraint validation API، چند صفت جدید، مقدارهای جدیدی برای {{ HTMLElement("input") }} صفت {{ htmlattrxref("type", "input") }} و عنصر جدید {{ HTMLElement("output") }}.
+
عنصرهای معناگرای جدید
+
علاوه بر عنصرهای بخش‌بندی، رسانه و فرم، عنصرهای متعددی مانند {{ HTMLElement("mark") }}، {{ HTMLElement("figure") }}، {{ HTMLElement("figcaption") }}، {{ HTMLElement("data") }}، {{ HTMLElement("time") }}، {{ HTMLElement("output") }}، {{ HTMLElement("progress") }}، یا {{ HTMLElement("meter") }} تعداد عنصرهای مجاز HTML5 را افرایش می‌دهند.
+
بهبودهای ایجادشده در {{HTMLElement("iframe")}}
+
با استفاده از صفت‌های{{htmlattrxref("sandbox", "iframe")}}، {{htmlattrxref("seamless", "iframe")}} و {{htmlattrxref("srcdoc", "iframe") }} توسعه‌دهندگان می‌توانند میزان امنیت و کارکرد یک عنصر {{HTMLElement("iframe")}} را به دقت بررسی کنند.
+
MathML
+
استفاده از فرمول‌های ریاضی را به صورت مستقیم در کد، ممکن می‌سازد.
+
مقدمه‌ای بر HTML5
+
این مقاله به معرفی مشکلات موجود HTML5 که در طراحی وب یا برنامه‌ی وب ممکن است وجود داشته باشند، می‌پردازد.
+
مفسر منطبق بر HTML5
+
مفسر، که بایت به بایت از یک سند HTML را به درخت DOM تبدیل می‌کند، گسترش یافته‌است و به دقت رفتاری که در تمامی حالت‌ها پیش می‌آید بررسی کرده، حتی کد نامعتبر HTML را، که منجر به بهینه‌تر شدن و قابل‌پیش‌بینی‌تر شدن مرورگرهای منطبق با HTML5 می‌شود.
+
+ +

Connectivity (اتصال)

+ +
+
Web Sockets
+
اجازه‌ی برقراری یک ارتباط پایدار بین صفحه و سرور را می‌دهد که از طریق آن می‌توان به مبادله‌ی داده‌هایی غیر از سند HTML پرداخت.
+
رخدادهای سمت سرور
+
سابق بر این سرور تنها با دریافت درخواست از مرورگر (کاربر) می‌توانست به آن پاسخ دهد اما الان می‌تواند این کار را بدون درخواست مرورگر نیز انجام دهد.
+
WebRTC
+
این فناوری، که مخفف Real-Time Communication یا ارتباط بلادرنگ است، اجازه‌ی برقراری ارتباط با سایر افراد و کنترل ویدیوکنفرانس به طور مستقیم از مرورگر را می‌هد بدون آن‌که به افزونه‌ای خاص یا برنامه‌ای خارجی نیاز باشد.
+
+ +

Offline & storage (ذخیره‌سازی آفلاین)

+ +
+
منابع آفلاین: حافظه‌ی نهان برنامه
+
Firefox به طور کامل منابع آفلاین در HTML5 را پشتیبانی می‌کند. سایر مرورگرها نیز این ویژگی را کمابیش پشتیبانی می‌کنند.
+
رخدادهای آنلاین و آفلاین
+
Firefox 3 مستندات WHATWG درباره‌ی رخدادهای آنلاین و آفلاین را پشتیبانی می‌کند، که به برنامه‌ها اجازه می‌دهد تشخیص بدهند آیا یک اتصال اینترنت فعال موجود است یا خیر، یا اینکه آیا یک اتصال قطع و وصل می‌شود یا خیر.
+
نشست سمت-مرورگر WHATWG و ذخیره‌سازی پایدار (در برابر ذخیره‌سازی DOM)
+
نشست سمت-مرورگر و ذخیره‌سازی پایدار به برنامه‌های وب اجازه می‌دهند که ساختارداده‌های مورد نیاز خود را در مرورگر کاربر ذخیره‌سازی کنند.
+
IndexedDB
+
یک استاندارد وب است که برای ذخیره‌سازی داده‌ها با حجم بالا در مرورگر کاربر به کار می‌رود و برای جستجوهای با سرعت بالا بر این داده‌ها با استفاده از اندیس‌ها، صورت می‌پذیرد.
+
استفاده از فایل‌ها توسط برنامه‌های وب
+
پشتیبانی از API جدید فایل در HTML5 به Gecko اضافه‌شده است تا برنامه‌های وب بتوانند به فایل‌هایی که کاربر انتخاب می‌کنند دسترسی داشته باشند، که این امر شامل پشتیبانی از فایل‌های چندگانه  با استفاده از عنصر {{ HTMLElement("input") }} که از نوع فایل می‌باشد، می‌شود یا صفت جدید multiple. همچنین FileReader نیز وجود دارد.
+
+ +

Multimedia (چندرسانه‌ای)

+ +
+
استفاده از audio و vedio در HTML5
+
عنصرهای {{ HTMLElement("audio") }} و {{ HTMLElement("video") }} با قرارگرفتن در صفحه، اجازه‌ی تغییراتی جدید در نحوه‌ی اجرای محتوای چندرسانه‌ای را می‌دهند.
+
WebRTC
+
این فناوری، که مخفف Real-Time Communication یا ارتباط بلادرنگ است، اجازه‌ی برقراری ارتباط با سایر افراد و کنترل ویدیوکنفرانس به طور مستقیم از مرورگر را می‌هد بدون آن‌که به افزونه‌ای خاص یا برنامه‌ای خارجی نیاز باشد.
+
استفاده از API دوربین
+
اجازه‌ی استفاده، تغییر و ذخیره‌سازی یک تصویر (عکس) را از دوربین رایانه‌ی کاربر می‌دهد.
+
+ +

3D, graphics & effects (سه‌بعدی، گرافیک و جلوه‌های تصویری)

+ +
+
خودآموز Canvas
+
درباره‌ی عنصر جدید {{ HTMLElement("canvas") }} و چگونگی رسم نمودارها و سایر اشیا در Firefox بیاموزید.
+
API متن HTML5 برای عنصرهای <canvas>
+
API متن در HTML5 توسط عنصرهای {{ HTMLElement("canvas") }} پشتیبانی می‌شوند.
+
WebGL
+
WebGL گرافیک سه‌بعدی را با معرفی APIای که بسیار نزدیک به OpenGL ES 2.0 عمل می‌کند، به صفحات وب می‌آورد که می‌تواند در عنصرهای {{ HTMLElement("canvas") }} در HTML5 به کار رود.
+
SVG
+
فرمتی مبتنی بر XML از تصاویر برداری که به صورت مستقیم می‌تواند در سند HTML به کار رود.
+
+ +
+
+
+ +
+

Performance & integration (عملکرد و جامعیت)

+ +
+
Web Workers
+
به فایل‌های JavaScript اجازه می‌دهد که در پس‌زمینه و بدون این‌که رخدادهای فعال را درگیر خود سازند، اجرا شوند.
+
XMLHttpRequest سطح ۲
+
اجازه‌ی برقراری ارتباط بخشی از صفحه با سرور را می‌دهد، تا محتوای پویا را بر اساس فعالیت کاربران یا زمان تغییر دهد. این فناوری پایه و اساس Ajax است.
+
JIT - کامپایل‌کردن موتورهای JavaScript
+
نسل‌ جدید موتورهای JavaScript بسیار قدرتمندتر از نسل قبلی هستند که در اجرا و عملکرد برنامه‌های JavaScript بسیار تاثیرگذار هستند.
+
History API
+
اجازه‌ی دستکاری تاریخچه (history) مرورگر را می‌دهد که این کار برای صفحاتی که شامل اطلاعات جدید هستند، مفید می‌باشد.
+
صفت contentEditable: وب‌سایت خود را به یک wiki تبدیل کنید!
+
HTML5 صفت contentEditable را استاندارد کرده است. درباره‌ی این ویژگی بیشتر بدانید.
+
کشیدن و رهاکردن
+
API کشیدن و رهاکردن در HTML5 پشتیبانی از این عملیات را در وب‌سایت‌ها و بین‌ وبسایت‌ها میسر می‌کند. همچنین یک API ساده‌تر را جهت استفاده در extensionها و برنامه‌های مبتنی بر Mozilla شامل می‌شود.
+
مدیریت Focus در HTML
+
صفت‌های جدید activeElement و hasFocus  در HTML5 پشتیبانی می‌شوند.
+
protocol handlerهای مبتنی بر وب
+
شما اکنون می‌توانید برنامه‌های وب را با استفاده از متد navigator.registerProtocolHandler() به عنوان protocol handler ثبت کنید.
+
requestAnimationFrame
+
اجازه‌ی کنترل رندرشدن انیمیشن‌ها را برای دستیابی به عملکردی بهینه، می‌دهد.
+
Fullscreen API
+
چگونگی استفاده از حالت تمام‌صفحه را کنترل می‌کند، بدون این‌که واسط کاربری (پیش‌فرض) مرورگر نمایش داده شود.
+
Pointer Lock API
+
اجازه‌ی قفل شدن اشاره‌گر (ماوس) روی محتوا را می‌دهد، تا بازی‌ها و برنامه‌های مشابه دیگر مشکل از دست‌رفتن focus را نداشته باشند.
+
رخدادهای آنلاین و آفلاین
+
برای ایجاد یک برنامه‌ی وب با قابلیت اجرای آفلاین، شما باید بدانید چه زمانی برنامه‌ی شما واقعا در حالت آفلاین قرار می‌گیرد. همین‌طور باید بدانید چه زمانی برنامه‌ی شما در حالت آفلاین باز می‌گردد.
+
+ +

Device access (دسترسی از طریق سایر دستگاه‌ها)

+ +
+
استفاده از API دوربین
+
اجازه‌ی استفاده، تغییر و ذخیره‌سازی یک تصویر (عکس) را از دوربین رایانه‌ی کاربر می‌دهد.
+
رخدادهای Touch
+
handlerهایی که به رخدادهای ایجادشده توسط کاربری که با صفحه‌ی لمسی کار می‌کند، پاسخ می‌دهد.
+
استفاده از geolocation
+
این اجاره را به مرورگر می‌دهد تا موقعیت جغرافیایی کاربر را شناسایی کند.
+
شناسایی جهت دستگاه
+
این اجازه را به مرورگر می‌دهد تا هرگاه جهت دستگاهی که مرورگر روی آن کار می‌کند تغییر یافت، اطلاعات آن را دریافت کند. از این ویژگی می‌توان به عنوان یک دستگاه ورودی استفاده کرد برای نمونه (ساخت بازی‌هایی که به تغییر جهت دستگاه واکنش نشان می‌دهند یا منطبق ساختن ظاهر یک صفحه با جهت نمایش دستگاه - افقی یا عمودی).
+
Pointer Lock API
+
اجازه‌ی قفل شدن اشاره‌گر (ماوس) روی محتوا را می‌دهد، تا بازی‌ها و برنامه‌های مشابه دیگر مشکل از دست‌رفتن focus را نداشته باشند.
+
+ +

Styling (سبک‌دهی)

+ +

CSS گسترش یافته است تا سبک‌دهی به عنصرها را به حالتی پیشرفته‌تر منتقل کند. از این ویژگی‌ها اغلب به عنوان CSS3 یاد می‌شود، از این رو CSS دیگر یک استاندارد یک‌پارچه نیست و ماژول‌های مختلف آن در سطح ۳ نیستند، بعضی در سطح ۱ و بعضی در سطح ۴، با تمام سطح‌های میانی که وجود دارند.

+ +
+
ویژگی‌های جدید در سبک‌دهی تصویر پس‌زمینه
+
اکنون ایجاد سایه در یک عنصر (جعبه) با استفاده از {{ cssxref("box-shadow") }} میسر است و تصویرهای پس‌زمینه‌ی چندگانه قابل استفاده هستند.
+
حاشیه‌هایی جذاب‌تر
+
اکنون نه تنها می‌توان با استفاده از تصویر‌ها و به کارگیری {{ cssxref("border-image") }} ،‌حاشیه‌ی عنصرها را ایجاد کرد بلکه کناره‌های گرد (rounded-borders) نیز با استفاده از ویژگی {{ cssxref("border-radius") }} قابل پیاده‌سازی هستند.
+
پویانمایی
+
با استفاده از تبدیلات در CSS برای پویانمایی بین حالت‌های مختلف یا از پویانمایی در CSS جهت پویانمایی بخشی از صفحه بدون نیاز به رخدادهای جاوااسکریپت، شما می‌توانید عنصرهای متحرک در صفحه‌ی خود را کنترل کنید.
+
بهبودهای ایجاد شده در Typography
+
توسعه‌دهندگان برای دسترسی به Typography بهتر اکنون کنترل بیشتری دارند. آن‌ها می‌توانند {{ cssxref("text-overflow") }} و فاصله‌گذاری را کنترل کنند، همچنین سایه‌ای که به متن اعمال می‌شود یا جزییات‌متن را به دقت کنترل کنند. به لطف ویژگی {{ cssxref("@font-face") }} فونت‌های مختلفی را می‌توان به صفحه‌ی خود پیوست کرد.
+
لایه‌های نمایشی جدید
+
در راستای ارتقای انعطاف‌پذیری در طراحی، دو لایه‌ی جدید افزوده شده‌اند: CSS multi-column layout و CSS flexible box layout.
+
+
+
diff --git a/files/fa/web/html/applying_color/index.html b/files/fa/web/html/applying_color/index.html new file mode 100644 index 0000000000..99f2d980cf --- /dev/null +++ b/files/fa/web/html/applying_color/index.html @@ -0,0 +1,502 @@ +--- +title: اضافه کردن رنگ به عناصر با استفاده از سی اس اس +slug: Web/HTML/افزودن_رنگ +translation_of: Web/HTML/Applying_color +--- +
{{HTMLRef}}
+ +

The use of color is a fundamental form of human expression. Children experiment with color before they even have the manual dexterity to draw. Maybe that's why color is one of the first things people often want to experiment with when learning to develop web sites. With CSS, there are lots of ways to add color to your HTML elements to create just the look you want. This article is a primer introducing each of the ways CSS color can be used in HTML.

+ +

Fortunately, adding color to your HTML is actually really easy to do, and you can add color to nearly anything.

+ +

We're going to touch on most of what you'll need to know when using color, including a {{anch("Things that can have color", "list of what you can color and what CSS properties are involved")}}, {{anch("How to describe a color", "how you describe colors")}}, and how to actually {{anch("Using color", "use colors both in stylesheets and in scripts")}}. We'll also take a look at how to {{anch("Letting the user picka color", "let the user pick a color")}}.

+ +

Then we'll wrap things up with a brief discussion of how to {{anch("Using color wisely", "use color wisely")}}: how to select appropriate colors, keeping in mind the needs of people with differing visual capabilities.

+ +

Things that can have color

+ +

At the element level, everything in HTML can have color applied to it. Instead, let's look at things in terms of the kinds of things that are drawn in the elements, such as text and borders and so forth. For each, we'll see a list of the CSS properties that apply color to them.

+ +

At a fundamental level, the {{cssxref("color")}} property defines the foreground color of an HTML element's content and the {{cssxref("background-color")}} property defines the element's background color. These can be used on just about any element.

+ +

Text

+ +

Whenever an element is rendered, these properties are used to determine the color of the text, its background, and any decorations on the text.

+ +
+
{{cssxref("color")}}
+
The color to use when drawing the text and any text decorations (such as the addition of under- or overlines, strike-through lines, and so forth.
+
{{cssxref("background-color")}}
+
The text's background color.
+
{{cssxref("text-shadow")}}
+
Configures a shadow effect to apply to text. Among the options for the shadow is the shadow's base color (which is then blurred and blended with the background based on the other parameters). See {{SectionOnPage("/en-US/docs/Learn/CSS/Styling_text/Fundamentals", "Text drop shadows")}} to learn more.
+
{{cssxref("text-decoration-color")}}
+
By default, text decorations (such as underlines, strikethroughs, etc) use the color property as their colors. However, you can override that behavior and use a different color for them with the text-decoration-color property.
+
{{cssxref("text-emphasis-color")}}
+
The color to use when drawing emphasis symbols adjacent to each character in the text. This is used primarily when drawing text for East Asian languages.
+
{{cssxref("caret-color")}}
+
The color to use when drawing the {{Glossary("caret")}} (sometimes referred to as the text input cursor) within the element. This is only useful in elements that are editable, such as {{HTMLElement("input")}} and {{HTMLElement("textarea")}} or elements whose HTML {{htmlattrxref("contenteditable")}} attribute is set.
+
+ +

Boxes

+ +

Every element is a box with some sort of content, and has a background and a border in addition to whatever contents the box may have.

+ +
+
{{anch("Borders")}}
+
See the section {{anch("Borders")}} for a list of the CSS properties you can use to set the colors of a box's borders.
+
{{cssxref("background-color")}}
+
The background color to use in areas of the element that have no foreground content.
+
{{cssxref("column-rule-color")}}
+
The color to use when drawing the line separating columns of text.
+
{{cssxref("outline-color")}}
+
The color to use when drawing an outline around the outside of the element. This outline is different from the border in that it doesn't get space set aside for it in the document (so it may overlap other content). It's generally used as a focus indicator, to show which element will receive input events.
+
+ +

Borders

+ +

Any element can have a border drawn around it. A basic element border is a line drawn around the edges of the element's content. See {{SectionOnPage("/en-US/docs/Learn/CSS/Introduction_to_CSS/Box_model", "Box properties")}} to learn about the relationship between elements and their borders, and the article Styling borders using CSS to learn more about applying styles to borders.

+ +

You can use the {{cssxref("border")}} shorthand property, which lets you configure everything about the border in one shot (including non-color features of borders, such as its width, style (solid, dashed, etc.), and so forth.

+ +
+
{{cssxref("border-color")}}
+
Specifies a single color to use for every side of the element's border.
+
{{cssxref("border-left-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-top-color")}}, and {{cssxref("border-bottom-color")}}
+
Lets you set the color of the corresponding side of the element's border.
+
{{cssxref("border-block-start-color")}} and {{cssxref("border-block-end-color")}}
+
With these, you can set the color used to draw the borders which are closest to the start and end of the block the border surrounds. In a left-to-right writing mode (such as the way English is written), the block start border is the top edge and the block end is the bottom. This differs from the inline start and end, which are the left and right edges (corresponding to where each line of text in the box begins and ends).
+
{{cssxref("border-inline-start-color")}} and {{cssxref("border-inline-end-color")}}
+
These let you color the edges of the border closest to to the beginning and the end of the start of lines of text within the box. Which side this is will vary depending on the {{cssxref("writing-mode")}}, {{cssxref("direction")}}, and {{cssxref("text-orientation")}} properties, which are typically (but not always) used to adjust text directionality based on the language being displayed. For example, if the box's text is being rendered right-to-left, then the border-inline-start-color is applied to the right side of the border.
+
+ +

Other ways to use color

+ +

CSS isn't the only web technology that supports color. There are graphics technologies that are available on the web which also support color.

+ +
+
The HTML Canvas API
+
Lets you draw 2D bitmapped graphics in a {{HTMLElement("canvas")}} element. See our Canvas tutorial to learn more.
+
SVG (Scalable Vector Graphics)
+
Lets you draw images using commands that draw specific shapes, patterns, and lines to produce an image. SVG commands are formatted as XML, and can be embedded directly into a web page or can be placed in he page using the {{HTMLElement("img")}} element, just like any other type of image.
+
WebGL
+
The Web Graphics Library is an OpenGL ES-based API for drawing high-performance 2D and 3D graphics on the Web. See Learn WebGL for 2D and 3D graphics to find out more.
+
+ +

How to describe a color

+ +

In order to represent a color in CSS, you have to find a way to translate the analog concept of "color" into a digital form that a computer can use. This is typically done by breaking down the color into components, such as how much of each of a set of primary colors to mix together, or how bright to make the color. As such, there are several ways you can describe color in CSS.

+ +

For more detailed discussion of each of the color value types, see the reference for the CSS {{cssxref("<color>")}} unit.

+ +

Keywords

+ +

A set of standard color names have been defined, letting you use these keywords instead of numeric representations of colors if you choose to do so and there's a keyword representing the exact color you want to use. Color keywords include the standard primary and secondary colors (such as red, blue, or orange), shades of gray (from black to white, including colors like darkgray and lightgrey), and a variety of other blended colors including lightseagreen, cornflowerblue, and rebeccapurple.

+ +

See {{SectionOnPage("/en-US/docs/Web/CSS/color_value", "Color keywords", "code")}} for a list of all available color keywords.

+ +

RGB values

+ +

There are three ways to represent an RGB color in CSS.

+ +

Hexadecimal string notation

+ +

Hexadecimal string notation represents a color using hexadecimal digits to represent each of the color components (red, green, and blue). It may also include a fourth component: the alpha channel (or opacity). Each color component can be represented as a number between 0 and 255 (0x00 and 0xFF) or, optionally, as a number between 0 and 15 (0x0 and 0xF). All components must be specified using the same number of digits. If you use the single-digit notation, the final color is computed by using each component's digit twice; that is, "#D" becomes "#DD" when drawing.

+ +

A color in hexadecimal string notation always begins with the character "#". After that come the hexadecimal digits of the color code. The string is case-insensitive.

+ +
+
"#rrggbb"
+
Specifies a fully-opaque color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
+
"#rrggbbaa"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
+
"#rgb"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
+
"#rgba"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
+
+ +

As an example, you can represent the opaque color bright blue as "#0000ff" or "#00f". To make it 25% opaque, you can use "#0000ff44" or "#00f4".

+ +

RGB functional notation

+ +

RGB (Red/Green/Blue) functional notation, like hexadecimal string notation, represents colors using their red, green, and blue components (as well as, optionally, an alpha channel component for opacity). However, instead of using a string, the color is defined using the CSS function {{cssxref("color_value", "rgb()", "#rgb()")}}. This function accepts as its input parameters the values of the red, green, and blue components and an optional fourth parameter, the value for the alpha channel.

+ +

Legal values for each of these parameters are:

+ +
+
red, green, and blue
+
Each must be an {{cssxref("<integer>")}} value between 0 and 255 (inclusive), or a {{cssxref("<percentage>")}} from 0% to 100%.
+
alpha
+
The alpha channel is a number between 0.0 (fully transparent) and 1.0 (fully opaque). You can also specify a percentage where 0% is the same as 0.0 and 100% is the same as 1.0.
+
+ +

For example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%).

+ +

HSL functional notation

+ +

Designers and artists often prefer to work using the {{interwiki("wikipedia", "HSL and HSV", "HSL")}} (Hue/Saturation/Luminosity) color method. On the web, HSL colors are represented using HSL functional notation. The hsl() CSS function is very similar to the rgb() function in usage otherwise.

+ +
+
HSL color cylinder +
Figure 1. An HSL color cylinder. Hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. Saturation is a percentage of how much of the way between being a shade of gray and having the maximum possible amount of the given hue. As the value of luminance (or lightness) increases, the color transitions from the darkest possible to the brightest possible (from black to white). Image courtesy of user SharkD on Wikipedia, distributed under the CC BY-SA 3.0 license.
+
+
+ +

The value of the hue (H) component of an HSL color is an angle from red around through yellow, green, cyan, blue, and magenta (ending up back at red again at 360°) that identifies what the base color is. The value can be specified in any {{cssxref("<angle>")}} unit supported by CSS, including degrees (deg), radians (rad), gradians (grad), or turns (turn). But this doesn't control how vivid or dull, or how bright or dark the color is.

+ +

The saturation (S) component of the color specifies what percentage of the final color is comprised of the specified hue. The rest is defined by the grey level provided by the luminance (L) component.

+ +

Think of it like creating the perfect paint color:

+ +
    +
  1. You start with base paint that's the maximum intensity possible for a given color, such as  the most intense blue that can be represented by the user's screen. This is the hue (H) component: a value representing the angle around the color wheel for the vivid hue we want to use as our base.
  2. +
  3. Then select a greyscale paint that corresponds how bright you want the color to be; this is the luminance. Do you want it to be very bright and nearly white, or very dark and closer to black, or somewhere in between? This is specified using a percentage, where 0% is perfectly black and 100% is perfectly white. (regardless of the saturation or hue). In between values are a literal grey area.
  4. +
  5. Now that you have a grey paint and a perfectly vivid color, you need to mix them together. The saturation (S) component of the color indicates what percentage of the final color should be comprised of that perfectly vivid color. The rest of the final color is made up of the grey paint that represents the saturation.
  6. +
+ +

You can also optionally include an alpha channel, to make the color less than 100% opaque.

+ +

Here are some sample colors in HSL notation:

+ +
+ + +

{{EmbedLiveSample("hsl-swatches", 300, 260)}}

+
+ +
+

Note that when you omit the hue's unit, it's assumed to be in degrees (deg).

+
+ +

Using color

+ +

Now that you know what CSS properties exist that let you apply color to elements and the formats you can use to describe colors, you can put this together to begin to make use of color. As you may have seen from the list under {{anch("Things that can have color")}}, there are plenty of things you can color with CSS. Let's look at this from two sides: using color within a {{Glossary("stylesheet")}}, and adding and changing color using {{Glossary("JavaScript")}} code to alter the styles of elements.

+ +

Specifying colors in stylesheets

+ +

The easiest way to apply color to elements—and the way you'll usually do it—is to simply specify colors in the CSS that's used when rendering elements. While we won't use every single property mentioned previously, we'll look at a couple of examples. The concept is the same anywhere you use color.

+ +

Let's take a look at an example, starting by looking at the results we're trying to achieve:

+ +
{{EmbedLiveSample("Specifying_colors_in_stylesheets", 650, 150)}}
+ +

HTML

+ +

The HTML responsible for creating the above example is shown here:

+ +
<div class="wrapper">
+  <div class="box boxLeft">
+    <p>
+      This is the first box.
+    </p>
+  </div>
+  <div class="box boxRight">
+    <p>
+      This is the second box.
+    </p>
+  </div>
+</div>
+ +

This is pretty simple, using a {{HTMLElement("div")}} as a wrapper around the contents, which consists of two more <div>s, each styled differently with a single paragraph ({{HTMLElement("p")}}) in each box.

+ +

The magic happens, as usual, in the CSS, where we'll apply colors define the layout for the HTML above.

+ +

CSS

+ +

We'll look at the CSS to create the above results a piece at a time, so we can review the interesting parts one by one.

+ +
.wrapper {
+  width: 620px;
+  height: 110px;
+  margin: 0;
+  padding: 10px;
+  border: 6px solid mediumturquoise;
+}
+ +

The .wrapper class is used to assign styles to the {{HTMLElement("div")}} that encloses all of our other content. This establishes thesize of the container using {{cssxref("width")}} and {{cssxref("height")}} as well as its {{cssxref("margin")}} and {{cssxref("padding")}}.

+ +

Of more interest to our discussion here is the use of the {{cssxref("border")}} property to establish a border around the outside edge of the element. This border is a solid line, 6 pixels wide, in the color mediumturquoise.

+ +

Our two colored boxes share a number of properties in common, so next we establish a class, .box, that defines those shared properties:

+ +
.box {
+  width: 290px;
+  height: 100px;
+  margin: 0;
+  padding: 4px 6px;
+  font: 28px "Marker Felt", "Zapfino", cursive;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+}
+ +

In brief, .box establishes the size of each box, as well as the configuration of the font used within. We also take advantage of CSS Flexbox to easily center the contents of each box. We enable flex mode using {{cssxref("display", "display: flex")}}, and set both {{cssxref("justify-content")}} and {{cssxref("align-items")}} to center. Then we can create a class for each of the two boxes that defines the propeties that differ between the two.

+ +
.boxLeft {
+  float: left;
+  background-color: rgb(245, 130, 130);
+  outline: 2px solid darkred;
+}
+ +

The .boxLeft class—which, cleverly, is used to style the box on the left—floats the box to the left, then sets up the colors:

+ + + +
.boxRight {
+  float: right;
+  background-color: hsl(270deg, 50%, 75%);
+  outline: 4px dashed rgb(110, 20, 120);
+  color: hsl(0deg, 100%, 100%);
+  text-decoration: underline wavy #88ff88;
+  text-shadow: 2px 2px 3px black;
+}
+ +

Finally, the .boxRight class describes the unique properties of the box that's drawn on the right. It's configured to float the box to the right so that it appears next to the previous box. Then the following colors are established:

+ + + +

Letting the user pick a color

+ +

There are many situations in which your web site may need to let the user select a color. Perhaps you have a customizable user interface, or you're implementing a drawing app. Maybe you have editable text and need to let the user choose the text color. Or perhaps your app lets the user assign colors to folders or items. Although historically it's been necessary to implement your own {{interwiki("wikipedia", "color picker")}}, HTML now provides support for browsers to provide one for your use through the {{HTMLElement("input")}} element, by using "color" as the value of its {{htmlattrxref("type", "input")}} attribute.

+ +

The <input> element represents a color only in the {{anch("Hexadecimal string notation", "hexadecimal string notation")}} covered above.

+ +

Example: Picking a color

+ +

Let's look at a simple example, in which the user can choose a color. As the user adjusts the color, the border around the example changes to reflect the new color. After finishing up and picking the final color, the color picker's value is displayed.

+ +

{{EmbedLiveSample("Example_Picking_a_color", 525, 275)}}

+ +
+

On macOS, you indicate that you've finalized selection of the color by closing the color picker window.

+
+ +

HTML

+ +

The HTML here creates a box that contains a color picker control (with a label created using the {{HTMLElement("label")}} element) and an empty paragraph element ({{HTMLElement("p")}}) into which we'll output some text from our JavaScript code.

+ +
<div id="box">
+  <label for="colorPicker">Border color:</label>
+  <input type="color" value="#8888ff" id="colorPicker">
+  <p id="output"></p>
+</div>
+ +

CSS

+ +

The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won't last, courtesy of the JavaScript below...

+ +
#box {
+  width: 500px;
+  height: 200px;
+  border: 2px solid rgb(245, 220, 225);
+  padding: 4px 6px;
+  font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"
+}
+ +

JavaScript

+ +

The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element.

+ +
let colorPicker = document.getElementById("colorPicker");
+let box = document.getElementById("box");
+let output = document.getElementById("output");
+
+box.style.borderColor = colorPicker.value;
+
+colorPicker.addEventListener("input", function(event) {
+  box.style.borderColor = event.target.value;
+}, false);
+
+colorPicker.addEventListener("change", function(event) {
+  output.innerText = "Color set to " + colorPicker.value + ".";
+}, false);
+ +

The {{event("input")}} event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker. Each time this event arrives, we set the box's border color to match the color picker's current value.

+ +

The {{event("change")}} event is received when the color picker's value is finalized. We respond by setting the contents of the <p> element with the ID "output" to a string describing the finally selected color.

+ +

Using color wisely

+ +

Making the right choices when selecting colors when designing a web site can be a tricky process, especially if you aren't well-grounded in art, design, or at least basic color theory. The wrong color choice can render your site unattractive, or even worse, leave the content unreadable due to problems with contrast or conflicting colors. Worse still, if using the wrong colors can result in your content being outright unusable by people withcertain vision problems, particularly color blindness.

+ +

Finding the right colors

+ +

Coming up with just the right colors can be tricky, especially without training in art or design. Fortunately, there are tools available that can help you. While they can't replace having a good designer helping you make these decisions, they can definitely get you started.

+ +

Base color

+ +

The first step is to choose your base color. This is the color that in some way defines your web site or the subject matter of the site. Just as we associate green with the beverage {{interwiki("wikipedia", "Mountain Dew")}} and one might think of the color blue in relationship with the sky or the ocean, choosing an appropriate base color to represent your site is a good place to start. There are plenty of ways to select a base color; a few ideas include:

+ + + +

When trying to decide upon a base color, you may find that browser extensions that let you select colors from web content can be particularly handy. Some of these are even specifically designed to help with this sort of work. For example, the web site ColorZilla offers an extension (Chrome / Firefox) that offers an eyedropper tool for picking colors from the web. It can also take averages of the colors of pixels in various sized areas or even a selected area of the page.

+ +
+

The advantage to averaging colors can be that often what looks like a solid color is actually a surprisingly varied number of related colors all used in concert, blending to create a desired effect. Picking just one of these pixels can result in getting a color that on its own looks very out of place.

+
+ +

Fleshing out the palette

+ +

Once you have decided on your base color, there are plenty of online tools that can help you build out a palette of appropriate colors to use along with your base color by applying color theory to your base color to determine appropriate added colors. Many of these tools also support viewing the colors filtered so you can see what they would look like to people with various forms of color blindness. See {{anch("Color and accessibility")}} for a brief explanation of why this matters.

+ +

A few examples (all free to use as of the time this list was last revised):

+ + + +

When designing your palette, be sure to keep in mind that in addition to the colors these tools typically generate, you'll probably also need to add some core neutral colors such as white (or nearly white), black (or nearly black), and some number of shades of gray.

+ +
+

Usually, you are far better off using the smallest number of colors possible. By using color to accentuate rather than adding color to everything on the page, you keep your content easy to read and the colors you do use have far more impact.

+
+ +

Color theory resources

+ +

A full review of color theory is beyond the scope of this article, but there are plenty of articles about color theory available, as well as courses you can find at nearby schools and universities. A couple of useful resources about color theory:

+ +
+
Color Science (Khan Academy in association with Pixar)
+
An online course which introduces concepts such as what color is, how it's percieved, and how to use colors to express ideas. Presented by Pixar artists and designers.
+
{{interwiki("wikipedia", "Color theory")}} on Wikipedia
+
Wikipedia's entry on color theory, which has a lot of great information from a technical perspective. It's not really a resource for helping you with the color sleection process, but is still full of useful information.
+
+ +

Color and accessibility

+ +

There are several ways color can be an {{Glossary("accessibility")}} problem. Improper or careless use of color can result in a web site or app that a percentage of your target audience may not be able to use adequately, resulting in lost traffic, lost business, and possibly even a public relations problem. So it's important to consider your use of color carefully.

+ +

You should do at least basic research into {{interwiki("wikipedia", "color blindness")}}. There are several kinds; the most common is red-green color blindness, which causes people to be unable to differentiate between the colors red and green. There are others, too, ranging from inabilities to tell the difference between certain colors to total inability to see color at all.

+ +
+

The most important rule: never use color as the only way to know something. If, for example, you indicate success or failure of an operation by changing the color of a shape from white to green for success and red for failure, users with red-green color-blindness won't be able to use your site properly. Instead, perhaps use both text and color together, so that everyone can understand what's happening.

+
+ +

For more information about color blindness, see the following articles:

+ + + +

Palette design example

+ +

Let's consider a quick example of selecting an appropriate color palette for a site. Imagine that you're building a web site for a new game that takes place on the planet Mars. So let's do a Google search for photos of Mars. Lots of good examples of Martian coloration there. We carefully avoid the mockups and the photos from movies. And we decide to use a photo taken by one of the Mars landers humanity has parked on the surface over the last few decades, since the game takes place on the planet's surface. We use a color picker tool to select a sample of the color we choose.

+ +

Using an eyedropper tool, we identify a color we like and determine that the color in question is #D79C7A, which is an appropriate rusty orange-red color that's so stereotypical of the Martian surface.

+ +

Having selected our base color, we need to build out our palette. We decide to use Paletton to come up with the other colors we need. Upon opening Paletton, we see:

+ +

Right after loading Paletton.

+ +

Next, we enter our color's hex code (D79C7A) into the "Base RGB" box at the bottom-left corner of the tool:

+ +

After entering base color

+ +

We now see a monochromatic palette based on the color we picked from the Mars photo. If you need a lot of related colors for some reason, those are likely to be good ones. But what we really want is an accent color. Something that will pop along side the base color. To find that, we click the "add complementary" toggle underneath the menu that lets you select the palette type (currently "Monochromatic"). Paletton computes an appropriate accent color; clicking on the accent color down in the bottom-right corner tells us that this color is #508D7C.

+ +

Now with complementary colors included.

+ +

If you're unhappy with the color that's proposed to you, you can change the color scheme, to see if you find something you like better. For example, if we don't like the proposed greenish-blue color, we can click the Triad color scheme icon, which presents us with the following:

+ +

Triad color scheme selected

+ +

That greyish blue in the top-right looks pretty good. Clicking on it, we find that it's #556E8D. That would be used as the accent color, to be used sparingly to make things stand out, such as in headlines or in the highlighting of tabs or other indicators on the site:

+ +

Triad color scheme selected

+ +

Now we have our base color and our accent. On top of that, we have a few complementary shades of each, just in case we need them for gradients and the like. The colors can then be exported in a number of formats so you can make use of them.

+ +

Once you have these colors, you will probably still need to select appropriate neutral colors. Common design practice is to try to find the sweet spot where there's just enough contrast that the text is crisp and readable but not enough contrast to become harsh for the eyes. It's easy to go too far in one way or another so be sure to get feedback on your colors once you've selected them and have examples of them in use available. If the contrast is too low, your text will tend to be washed out by the background, leaving it unreadable, but if your contrast is too high, the user may find your site garish and unpleasant to look at.

+ +

Color, backgrounds, contrast, and printing

+ +

What looks good on screen may look very different on paper. In addition, ink can be expensive, and if a user is printing your page, they don't necessarily need all the backgrounds and such using up their precious ink when all that matters is the text itself. Most browsers, by default, remove background images when printing documents.

+ +

If your background colors and images have been selected carefully and/or are crucial to the usefulness of the content, you can use the CSS {{cssxref("color-adjust")}} property to tell the browser that it should not make adjustments to the appearance of content.

+ +

The default value of color-adjust, economy, indicates that the browser is allowed to make appearance changes as it deems necessary in order to try to optimize the legibility and/or print economy of the content, given the type of output device the document is being drawn onto.

+ +

You can set color-adjust to exact to tell the browser that the element or elements on which you use it have been designed specifically to best work with the colors and images left as they are. With this set, the browser won't tamper with the appearance of the element, and will draw it as indicated by your CSS.

+ +
+

Note: There is no guarantee, though, that color-adjust: exact will result in your CSS being used exactly as given. If the browser provides user preferences to change the output (such as a "don't print backgrounds" checkbox in a print dialog box), that overrides the value of color-adjust.

+
+ +

See also

+ + diff --git a/files/fa/web/html/attributes/index.html b/files/fa/web/html/attributes/index.html new file mode 100644 index 0000000000..70c73bc06b --- /dev/null +++ b/files/fa/web/html/attributes/index.html @@ -0,0 +1,607 @@ +--- +title: مرجع صفت‌های HTML +slug: HTML/Attributes +translation_of: Web/HTML/Attributes +--- +

عنصرها در HTM صفت‌هایی دارند؛ این‌ها مقادیر اضافه‌ای هستند که عنصرها را پیکربندی می‌کنند یا رفتار آنها را در راه‌های گسترده‌ای به‌صورت مناسب با شرایطی که کاربران می‌خواهند تطبیق میدهند.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
نام صفتعنصرهاتوضیح
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}فهرست انواعی که سرور قبول می‌کند، معمولا از نوع فایل.
accept-charset{{ HTMLElement("form") }}فهرستی از مجموعه کاراکترهای پشتیبانی شده.
accesskeyGlobal attributeتعیین کلید میانبری از صفحه‌کلید جهت فعال‌سازی یا افزودن focus به عنصر مورد نظر.
action{{ HTMLElement("form") }}نشانی فایلی که قرار است اطلاعات ارسالی از فرم را پردازش کند.
align{{ HTMLElement("applet") }}, {{ HTMLElement("caption") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }},  {{ HTMLElement("hr") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }},  {{ HTMLElement("td") }},  {{ HTMLElement("tfoot") }} , {{ HTMLElement("th") }}, {{ HTMLElement("thead") }}, {{ HTMLElement("tr") }}تنظیمات مربوط به چینش عنصر را تعیین می‌کند.
alt +

{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}

+
متن جایگزین تصویر، زمانی که تصویر قابل نمایش نباشد.
async{{ HTMLElement("script") }}نشان‌دهنده‌ی این است که اسکریپت باید به صورت نامتقارن اجرا شود.
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}نشان‌دهنده‌ی این است که آیا کنترل‌های موجود در این فرم قابلیت اختیار مقادیر پیش‌فرض مرورگر را دارند یا خیر.
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}بعد از بارگذاری صفحه، عنصر مورد نظر focus را به خود می‌گیرد.
autoplay{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}پخش صوت یا تصویر به محض آماده شدن.
bgcolor{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} +

رنگ پیش‌زمینه‌ی عنصر.

+

یادداشت: این یک صفت قدیمی است که باید از ویژگی {{ Cssxref("background-color") }} در CSS به جای آن استفاده کرد.

+
border{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} +

نشان‌دهنده‌ی حاشیه‌ی عنصر مورد نظر.

+

یادداشت: این یک صفت قدیمی است که باید از ویژگی {{ Cssxref("border") }} در CSS به جای آن استفاده کرد.

+
buffered{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}شامل بازه‌ی زمانی است که محتوای مورد نظر در آن بازه بافر شده است.
challenge{{ HTMLElement("keygen") }}رشته‌ای از حروف که به همراه کلید عمومی ارسال می‌شود.
charset{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}نوع کدگذاری کاراکترهای موجود در صفحه یا اسکریپت را تعیین می‌کند.
checked{{ HTMLElement("command") }}, {{ HTMLElement("input") }}نشان‌دهنده‌ی این است که آیا عنصر مورد نظر در زمان بارگذاری صفحه باید انتخاب شود یا خیر.
cite{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}به نشانی منبع نقل قول اشاره می‌کند.
classGlobal attributeاغلب به همراه CSS به کار می‌رود تا عنصرهایی با ویژگی‌های مشترک را سبک‌دهی کند.
code{{ HTMLElement("applet") }}نشانی فایل با پیشوند class که اپلت برای بارگذاری و اجراشدن به آن نیاز دارد را، شامل می‌شود.
codebase{{ HTMLElement("applet") }}این صفت نشانی مطلق یا نسبی دایرکتوری که فایل‌های با پیشوند class مورد نیاز اپلت هستند، را شامل می‌شود.
color{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} +

این صفت رنگ متن را با توجه به دو الگوی "نام رنگ" یا "مقدار هگزادسیمال رنگ" مشخص می‌کند.

+

یادداشت: این یک صفت قدیمی است که باید از ویژگی {{ Cssxref("color") }} در CSS به جای آن استفاده کرد.

+
cols{{ HTMLElement("textarea") }}تعداد ستون‌های ناحیه‌ی متنی را مشخص می‌کند.
colspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}تعداد ستون‌های یک سلول (خانه) از جدول را مشخص می‌کند.
content{{ HTMLElement("meta") }}مقداری که منطبق با http-equiv یا name است.
contenteditableGlobal attributeنشان‌دهنده‌ی این است که آیا محتوای عنصر قابل ویرایش هستنند یا خیر.
contextmenuGlobal attributeID یک {{ HTMLElement("menu") }} را به عنوان منو تعیین می‌کند.
controls{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}نشان‌دهنده‌ی این است که آیا مرورگر دکمه‌های کنترل فایل صوتی یا تصویری را باید نشان بدهد یا خیر.
coords{{ HTMLElement("area") }}مجموعه‌ای از مقادیر که نشان‌دهنده‌ی مختصات ناحیه‌ی مورد نظر هستند.
data{{ HTMLElement("object") }}نشانی منبع مورد نیاز را تعیین می‌کند.
datetime{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}نشان‌دهنده‌ی تاریخ و زمان به کار رفته در عنصر مورد نظر است.
default{{ HTMLElement("track") }}نشان‌دهنده‌ی این است که track قبل از اینکه تنظیمات کاربر تغییر کند، باید فعال شود.
defer{{ HTMLElement("script") }}نشان‌دهنده‌ی این است که اسکریپت بلافاصله بعد از بارگذاری و تفسیر صفحه باید اجرا شود.
dirGlobal attributeجهت نوشته‌شدن متن را مشخص می‌کند. مقادیر قابل قبول عبارتند از ltr (چپ به راست)و rtl (راست به چپ)
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} 
disabled{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}نشان‌دهنده‌ی این است که آیا کاربر امکان تعامل با عنصر مورد نظر را دارد یا خیر.
draggableGlobal attributeقابلیت کشیده‌شدن عنصر (کلیک بر روی آن و حرکت دادنش) را تعیین می‌کند.
dropzoneGlobal attributeناحیه‌ای که عنصر کشیده‌شده را می‌توان در آن رها (drop) کرد.
enctype{{ HTMLElement("form") }}وقتی از method ای مانند POST برای ارسال مقادیر فرم استفاده می‌شود، این صفت نوع محتوای داده‌ای را در فرم تعیین می‌کند.
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}تعیین عنصرهایی که به عنصر مورد نظر تعلق دارند.
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}نشان‌دهنده‌ی فرمی است که مالک (پدر) عنصر مورد نظر است.
headers{{ HTMLElement("td") }}, {{ HTMLElement("th") }}IDهای عنصر(های) <th> که به این عنصر مربوط می‌شوند.
height{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} +

در برخی کاربردها مانند {{ HTMLElement("div") }}، این یک صفت قدیمی است که باید از ویژگی {{ Cssxref("height") }} در CSS به جای آن استفاده کرد. در سایر موارد مانند {{ HTMLElement("canvas") }} استفاده از این صفت ضروری است.

+
hiddenGlobal attributeارتباط یک عنصر را نشان می‌دهد.
high{{ HTMLElement("meter") }}پایین‌ترین مرز از بالاترین محدوده را نشان می‌دهد.
href{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }}نشانی منبعی که پیوند (لینک) به آن اشاره دارد.
hreflang{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}زبان منبعی که پیوند (لینک) به آن اشاره دارد.
http-equiv{{ HTMLElement("meta") }} 
icon{{ HTMLElement("command") }}تصویری که نشان‌دهنده‌ی command باشد را تعیین می‌کند.
idGlobal attributeاغلب با CSS به کار می‌رود تا عنصر مورد نظر را سبک دهی کند. مقدار این صفت باید منحصر به فرد (یکتا) باشد.
ismap{{ HTMLElement("img") }}نشان‌دهنده‌ی این است که آیا تصویر بخشی از یک image map سمت سرور می‌باشد یا خیر.
itempropGlobal attribute 
keytype{{ HTMLElement("keygen") }}نوع کلید تولید شده را مشخص می‌کند.
kind{{ HTMLElement("track") }}گونه‌ی متنی track را مشخص می‌کند.
label{{ HTMLElement("track") }}متنی خوانا برای track مشخص می‌کند.
langGlobal attributeزبانی که در عنصر مورد نظر به کار رفته است را مشخص می‌کند.
language{{ HTMLElement("script") }}زبان اسکریپت را در عنصر مورد نظر تعیین می‌کند.
list{{ HTMLElement("input") }}فهرستی از گزینه‌های از پیش تعریف شده را برای کاربر مشخص می‌کند.
loop{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}نشان‌دهنده‌ی این است که آیا محتوای مورد نظر (متن، صوت یا تصویر) پس از تمام شدن، دوباره باید اجرا شود یا به نمایش دربیاید یا خیر.
low{{ HTMLElement("meter") }}بالاترین مرز از پایین‌ترین محدوده را نشان می‌دهد.
manifest{{ HTMLElement("html") }}نشانی فایل cache manifest (جهت مرور آفلاین صفحات) را در سند مشخص می‌کند.
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}نشان‌دهنده‌ی بیشترین مقدار مجاز است.
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}بیشترین تعداد کاراکترها را در عنصر مورد نظر تعیین می‌کند.
media{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}بخش کوچکی از رسانه که منبع پیوند داده شده برای آن طراحی شده است، را مشخص می‌کند.
method{{ HTMLElement("form") }}مشخص می‌کند که از کدام متد HTTP برای ارسال داده‌های فرم استفاده شود، که می‌تواند GET (پیش‌فرض) یا POST باشد.
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}نشان‌دهنده‌ی کمترین مقدار مجاز است.
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }} +

نشان‌دهنده‌ی این است که آیا مقدارهای چندتایی می‌توانند در ورودی‌های email یا file وارد شوند یا خیر.

+
name{{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}, {{ HTMLElement("map") }}, {{ HTMLElement("meta") }}, {{ HTMLElement("param") }} +

نام عنصر. برای نمونه از این صفت برای شناسایی فیلدهای مورد نظر که به سمت سرور ارسال شده‌اند استفاده می‌شود.

+
novalidate{{ HTMLElement("form") }} +

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

+
open{{ HTMLElement("details") }} +

نشان‌دهنده‌ی این است که آیا جزییات زمان بارگذاری صفحه نمایش داده می‌شوند یا خیر.

+
optimum{{ HTMLElement("meter") }} +

نشان‌دهنده‌ی مقدار عددی بهینه است.

+
pattern{{ HTMLElement("input") }} +

عبارتی منظم را تعریف می‌کند که مقدار عنصر مورد نظر برابر آن مورد سنجش و ارزیابی قرار می‌گیرد.

+
ping{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} +

با نمایش کادری کوچک به کاربر اطلاع می‌دهد که چه چیزی در فیلد قابل نوشتن است.

+
poster{{ HTMLElement("video") }} +

نشانی که به یک فریم از فیلم اشاره دارد تا زمانی که کاربر هنوز اقدام به پخش فیلم نکرده است به وی نمایش داده شود.

+
preload{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}نشان‌دهنده‌ی این است که آیا تمام منبع، بخشی از آن یا هیچ چیز باید از قبل از اقدام کاربر برای پخش محتوا، بارگذاری شود.
pubdate{{ HTMLElement("time") }} +

نشان‌دهنده‌ی این است که آیا این تاریخ و زمان مطابق با تاریخ نزدیک‌ترین عنصر {{ HTMLElement("article") }} والد خود است یا خیر.

+
radiogroup{{ HTMLElement("command") }} 
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} +

نشان‌دهنده‌ی این است که آیا این عنصر قابل ویرایش است یا خیر.

+
rel{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}ارتباط بین شی هدف و شی پینوندی را مشخص می‌کند.
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}نشان‌دهنده‌ی این است که آیا این عنصر (از فرم) نیاز به تکمیل شدن از طرف کاربر دارد یا خیر.
reversed{{ HTMLElement("ol") }}نشان‌دهنده‌ی این است که آیا فهرست باید به ترتیب نزولی نمایش داده شود، بر خلاف ترتیب صعودی.
rows{{ HTMLElement("textarea") }}تعداد سطرهای ناحیه‌ی متنی را مشخص می‌کند.
rowspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}تعداد سطرهایی که سلول (خانه) جدول باید بر اساس آن ایجاد شود را مشخص می‌‌کند.
sandbox{{ HTMLElement("iframe") }} 
spellcheckGlobal attributeنشان‌دهنده‌ی این است که آیا عملیات بررسی واژه‌ها برای این عنصر مجاز است یا خیر.
scope{{ HTMLElement("th") }} 
scoped{{ HTMLElement("style") }} 
seamless{{ HTMLElement("iframe") }} 
selected{{ HTMLElement("option") }}مقداری را تعیین می‌کند که در زمان بارگذاری صفحه، در فهرست انتخاب شده است.
shape{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}عرض عنصر را (بر اساس پیکسل) تعیین می‌کند. اگر عنصر مورد نظر از نوع text یا password باشد این صفت تعداد کاراکترهای عنصر را تعیین می‌کند.
sizes{{ HTMLElement("link") }} 
span{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }} 
src{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}نشانی فایلی که عنصر مورد نظر از آن به عنوان منبع استفاده می‌کند.
srcdoc{{ HTMLElement("iframe") }} 
srclang{{ HTMLElement("track") }} 
start{{ HTMLElement("ol") }}اولین عدد در فهرست را تعیین می‌کند، اگر غیر از ۱ باشد.
step{{ HTMLElement("input") }} 
styleGlobal attributeسبک‌های CSS را تعریف می‌کند که در صورت وجود فایل‌های قدیمی بر روی آن‌ها نوشته می‌شوند.
summary{{ HTMLElement("table") }} 
tabindexGlobal attributeبا ویرایش این صفت، ترتیب انتخاب شدن عنصر‌های صفحه در مرورگر به حالتی که برایش تعیین شود تغییر می‌یابد.
target{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }} 
titleGlobal attributeمتنی که در یک کادر کوچک با قرار دادن mouse روی عنصر مورد نظر نمایش می‌یابد.
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}نوع عنصر را تعریف می‌کند.
usemap{{ HTMLElement("img") }},  {{ HTMLElement("input") }}, {{ HTMLElement("object") }} 
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}مقدار پیش‌فرضی که در زمان بارگذاری صفحه برای عنصر انتخاب می‌شود را تعیین می‌کند.
width{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} +

در برخی موارد مانند {{ HTMLElement("div") }} این یک صفت قدیمی به حساب می‌آید که باید از ویژگی {{ Cssxref("width") }} در CSS به جای آن استفاده کرد. در سایر موارد مانند {{ HTMLElement("canvas") }} این یک صفت ضروری است که باید ذکر شود.

+
wrap{{ HTMLElement("textarea") }}نشان‌دهنده‌ی این است که آیا متن باید کوتاه شود یا خیر.
+

Content versus IDL attributes

+

In HTML, most attributes have two faces: the content attribute and the IDL attribute.

+

The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via {{domxref("element.setAttribute()")}} or {{domxref("element.getAttribute()")}}. The content attribute is always a string even when the expected value should be an integer. For example, to set an {{HTMLElement("input")}} element's maxlength to 42 using the content attribute, you have to callsetAttribute("maxlength", "42") on that element.

+

The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.

+

Most of the time, IDL attributes will return their valules as they are really used. For example, the default type for {{HTMLElement("input")}} elements is "text", so if you setinput.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, thetype IDL attribute will return the string "text".

+

IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, soinput.maxlength is always going to return a number and when you setinput.maxlength ,it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.

+

IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes  behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave.

+

See also

+ diff --git a/files/fa/web/html/tips_for_authoring_fast-loading_html_pages/index.html b/files/fa/web/html/tips_for_authoring_fast-loading_html_pages/index.html deleted file mode 100644 index 94048c4ba7..0000000000 --- a/files/fa/web/html/tips_for_authoring_fast-loading_html_pages/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: نکاتی درباره‌ی ایجاد صفحات HTML سریع -slug: Web/HTML/Tips_for_authoring_fast-loading_HTML_pages -translation_of: Learn/HTML/Howto/Author_fast-loading_HTML_pages ---- -

نکات زیر بر اساس دانش و تجربه به دست آمده‌اند.

-

یک صفحه‌ی وب بهینه نه تنها برای مخاطب‌های شما تعاملی‌تر است، بلکه روی وب‌سرور و اتصال اینترنت شما نیز تاثیرگذار است. این امر می‌تواند برای سایت‌هایی که ترافیک بالایی دارند مانند سایت‌های خبری، مساله‌ای اساسی باشد.

-

بهینه‌سازی عملکرد یک صفحه فقط برای کاربران با اینترنت کم سرعت مطرح نیست. بلکه برای آن دسته از کاربران با اینترنت پرسرعت نیز تاثیر به سزایی دارد.

-

نکته‌ها

-

کاهش دادن وزن صفحه

-

وزن صفحه، یکی از مهم‌ترین فاکتورهای بارگیری یک صفحه است.

-

کاهش وزن صفحه به این معنا است که با حذف کردن جاهای خالی و خطوط کمکی (comment) و با انتقال اسکریپت‌ها و برگه‌های سبک سلسله‌مراتبی به فایل‌های خارجی، سرعت بارگیری صفحه را تا حد امکان افزایش دهیم.

-

ابزاری مانند HTML Tidy می‌توانند به صورت خودکار جاهای خالی اضافی را از یک سند HTML حذف کنند. ابزار دیگری نیز وجود دارند که فایل‌های جاوااسکریپت را با تکنیک‌های فشرده‌سازی، فشرده کرده و با کاهش حجم آن‌ها باعث افزایش سرعت بارگیری صفحه می‌شوند.

-

کاهش تعداد فایل‌ها

-

با کاهش یافتن تعداد فایل‌های مورد نیاز یک صفحه، تعداد درخواست‌های HTTP جهت بارگیری صفحه نیز کاهش می‌یابد.

-

بسته به تنظیمات حافظه‌ی نهان مرورگر، ممکن است درخواست If-Modified-Since به وب‌سرور برای هر فایل CSS، جاوااسکریپت یا تصویر فرستاده شود که در آن مشخص می‌شود آیا فایل نسبت به آخرین باری که دانلود شده، تغییر کرده است یا خیر.

-

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

-

اگر از تصاویر پس‌زمینه در فایل CSS خود به نسبت زیادی استفاده می‌کنید می‌توانید با استفاده از تکینیکی به نام image sprite این تصاویر را با هم ترکیب کنید تا تعداد درخواست‌های ارسالی به سرور کاهش یابد. تنها کافی است با تغییر موقعیت تصویر در صفحه نحوه‌ی نمایش آن را در حالت‌های مختلف تنظیم کنید. این تکنیک برای عنصرهایی که ابعاد محدودی در صفحه دارند به خوبی کار می‌کند. اگرچه تعداد درخواست‌های http کمتر و cache کردن هر تصویر نیز می‌تواند به عنوان راه حل جایگزین مطرح باشد.

-

زمان زیادی که صرف می‌شود تا آخرین تاریخ تغییر یک فایل مشخص شود، می‌تواند منجر به تاخیر در نمایش اولیه از یک صفحه شود، چرا که مرورگر قبل از اینکه صفحه را پردازش کند باید زمان تغییر یا modification هر فایل  CSS یا جاوااسکریپت را بررسی کند.

-

کاهش تعداد ارجاع‌ها به دامنه‌های مختلف

-

از آن‌جایی که هر دامنه‌ی منحصر به فرد در فرآیند DNS Lookup هزینه‌ی زمانی دارد، زمان بارگذاری صفحه با توجه به تعداد دامنه‌های مختلف در فایل‌های CSS ،جاوااسکریپت و تصویرها افزایش می‌یابد.

-

با این حال همیشه به یاد داشته باشید تا آن‌جا که ممکن است از حداقل تعداد دامنه‌های مختلف در صفحات سایت استفاده کنید.

-

محتوای کاربردی را Cache کنید

-

اطمینان یابید هر محتوایی که قابل cache شدن است، این اتفاق برایش افتاده باشد و زمان پایانی cache نیز دارا باشد.

-

در حقیقت باید به فایل سرآیند (header) با نام Last-Modified توجه خاصی داشت. کار این فایل ذخیره‌سازی آخرین زمانی است که به صفحات ثابت (html و css و ...) از طریق user agent یا همان مرورگر بر اساس زمان موجود در وب سرور، ارجاع شده است. البته این موضوع در رابطه با صفحات پویا (php و aspx و ...) اتفاق نمی‌افتد، یعنی این فایل سرآیند ارسال نمی‌شود.

-

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

-
    -
  1. HTTP Conditional Get for RSS Hackers
  2. -
  3. HTTP 304: Not Modified
  4. -
  5. On HTTP Last-Modified and ETag
  6. -
-

ترتیب بهینه‌ی اجزای تشکیل دهنده‌ی صفحه

-

ابتدا محتوای صفحه بارگذاری شود، همراه با هرفایل CSS یا JavaScript که در نمایش اولیه‌ی آن تاثیر دارد، تا کاربر بتواند در کوتاه‌ترین زمان ممکن به محتوای صفحه دسترسی داشته باشد. این محتوا معمولا از متن تشکیل می‌شود که در زمان کوتاهی می‌تواند در اختیار کاربر قرار گیرد.

-

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

-

کاهش تعداد اسکریپت‌های برخط (inline)

-

این نوع اسکریپت‌ها می‌توانند زمان زیادی را به خود اختصاص دهند، چرا که parser باید در نظر بگیرد که یک اسکریپت برخط می‌تواند ساختار صفحه را هنگامی که خود صفحه در حال parse شدن است، تغییر دهد. کاهش تعداد این اسکریپت‌ها به صورت عمومی، و کاهش استفاده از document.write به صورت اختصاصی، می‌تواند منجر به افزایش سرعت در بارگذاری صفحات شود. همچنین استفاده از روش‌های پیشرفته در AJAX جهت تغییر در محتوای صفحه به جای استفاده از document.write توصیه می‌شود.

-

استفاده از CSS پیشرفته و عنصرهای معتبر

-

استفاده از CSS به صورت صحیح می‌تواند تعداد عنصرهای مورد نیاز در صفحه را به شکل قابل ملاحظه‌ای کاهش دهد. از جمله این تکنیک‌ها می‌توان به جایگزین کردن برخی تصاویر (که به spacer معروف هستند) با معادل CSS آن‌ها جهت قالب‌بندی صفحه اشاره کرد.

-

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

-

به علاوه، استفاده از عنصرهای معتبر این امکان را در اختیار سایر ابزار می‌گذارد تا صفحات سایت شما را بررسی (pre-process) کنند. برای نمونه، HTML Tidy می‌تواند فضای خالی در صفحات و تگ‌های پایانی اختیاری را حذف کند; اگرچه این ابزار در صفحاتی که دارای خطاهای بسیار در عنصرها باشند، اجرا نمی‌شود.

-

محتوا را طبقه‌بندی کنید

-

استفاده از جدول‌ها در قالب‌بندی صفحات یک روش منسوخ است که دیگر نباید استفاده شود. در عوض از عنصر {{ HTMLElement("div") }} و در آینده‌ی نزدیک از ساختار چند ستونی CSS3 یا ساختار منعطف جعبه‌ای CSS3 باید استفاده شود.

-

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

-

به جای این‌که از ساختاری مانند این استفاده کنید:

-
<TABLE>
-  <TABLE>
-    <TABLE>
-          ...
-    </TABLE>
-  </TABLE>
-</TABLE>
-

در عوض از جدول‌هایی که جداگانه هستند یا divها استفاده کنید.

-
<TABLE>...</TABLE>
-<TABLE>...</TABLE>
-<TABLE>...</TABLE>
-
-

همچنین می‌توانید مستندات CSS3 Multi-column Layout یا CSS3 Flexible Box Layout را مشاهده کنید.

-

مشخص کردن اندازه‌ی تصویرها و جدول‌ها

-

اگر مرورگر به محض دریافت تصویر یا جدول بتواند اندازه‌ی آن را تشخیص دهد، این امر موجب نمایش هر چه بهتر محتوای صفحه در زمان بارگذاری خواهد شد. به همین منظور استفاده از height و width برای تصویرها در هر جایی که ممکن است باید استفاده گردند.

-

برای جدول‌ها نیز می‌توان از قطعه کد CSS زیر استفاده کرد:

-
  table-layout: fixed;
-
-

همچنین باید از تگ‌های COL و COLGROUP برای مشخص کردن عرض جدول‌های استفاده کرد.

-

حداقل محدودیت‌های مرورگر را در نظر بگیرید

-

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

-

در حقیقت، حداقل پیش‌نیازهای شما باید منطبق با مرورگرهای پیشرفته‌ای باشند که استانداردهای وب را رعایت می‌کنند که این مرورگرها شامل Firefox 3.6 به بالا برای تمامی پلتفرم‌ها، Internet Explorer 8 به بالا در ویندوز، Opera 10 به بالا در ویندوز و Safari 4 به بالا در Mac OS X هستند.

-

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

-

ساختار صفحه‌ی مورد نظر ما

-

· HTML

-
-
- · HEAD
-
-
-
-
-
- · LINK ...
-
- فایل‌های CSS که جهت نمایش صفحه مورد نیاز هستند. تعداد این فایل‌ها را پایین نگه دارید تا عملکرد صفحه افزایش یابد. همچنین می‌توان سایر فایل‌های CSS نامربتط با این صفحه را در فایل‌های دیگر قرار داد.
-
-
-
-
-
-
-
- · SCRIPT ...
-
- فایل‌های JavaScript که موردنیاز توابعی هستند که در زمان بارگذاری صفحه فراخوانی می‌شوند. تعداد این فایل‌ها را جهت عملکرد بهتر صفحه، پایین نگه دارید.
-
-
-
-
-
- · BODY
-
- محتوای مورد نظر صفحه که در قالب جدول‌ها یا divها گردآوری شده‌اند. این محتوا می‌تواند جدا از سایر اجزای صفحه نمایش یابد.
-
-
-
-
-
- · SCRIPT ...
-
- هر اسکریپتی که در ساختار صفحه (DHTML) تغییر ایجاد می‌کند. این اسکریپت‌ها می‌توانند پس از بارگذاری تمام صفحه و نمایش محتوا به کاربر، اجرا شوند. بنابراین دلیلی ندارد که بارگذاری آن‌ها قبل از محتوا صورت گیرد که در این صورت نمایش محتوا به کاربر با تاخیر همراه می‌شود.
-
- اگر تصویری جهت حرکت‌های rollover در نظر گرفته‌اید، باید در این قسمت از صفحه preload یا پیش‌بارگذاری شوند، جایی که محتوای صفحه قبل از آن نمایش داده شده است.
-
-
-
- - -
-

Original Document Information

- -
-

 

diff --git "a/files/fa/web/html/\330\247\331\201\330\262\331\210\330\257\331\206_\330\261\331\206\332\257/index.html" "b/files/fa/web/html/\330\247\331\201\330\262\331\210\330\257\331\206_\330\261\331\206\332\257/index.html" deleted file mode 100644 index 99f2d980cf..0000000000 --- "a/files/fa/web/html/\330\247\331\201\330\262\331\210\330\257\331\206_\330\261\331\206\332\257/index.html" +++ /dev/null @@ -1,502 +0,0 @@ ---- -title: اضافه کردن رنگ به عناصر با استفاده از سی اس اس -slug: Web/HTML/افزودن_رنگ -translation_of: Web/HTML/Applying_color ---- -
{{HTMLRef}}
- -

The use of color is a fundamental form of human expression. Children experiment with color before they even have the manual dexterity to draw. Maybe that's why color is one of the first things people often want to experiment with when learning to develop web sites. With CSS, there are lots of ways to add color to your HTML elements to create just the look you want. This article is a primer introducing each of the ways CSS color can be used in HTML.

- -

Fortunately, adding color to your HTML is actually really easy to do, and you can add color to nearly anything.

- -

We're going to touch on most of what you'll need to know when using color, including a {{anch("Things that can have color", "list of what you can color and what CSS properties are involved")}}, {{anch("How to describe a color", "how you describe colors")}}, and how to actually {{anch("Using color", "use colors both in stylesheets and in scripts")}}. We'll also take a look at how to {{anch("Letting the user picka color", "let the user pick a color")}}.

- -

Then we'll wrap things up with a brief discussion of how to {{anch("Using color wisely", "use color wisely")}}: how to select appropriate colors, keeping in mind the needs of people with differing visual capabilities.

- -

Things that can have color

- -

At the element level, everything in HTML can have color applied to it. Instead, let's look at things in terms of the kinds of things that are drawn in the elements, such as text and borders and so forth. For each, we'll see a list of the CSS properties that apply color to them.

- -

At a fundamental level, the {{cssxref("color")}} property defines the foreground color of an HTML element's content and the {{cssxref("background-color")}} property defines the element's background color. These can be used on just about any element.

- -

Text

- -

Whenever an element is rendered, these properties are used to determine the color of the text, its background, and any decorations on the text.

- -
-
{{cssxref("color")}}
-
The color to use when drawing the text and any text decorations (such as the addition of under- or overlines, strike-through lines, and so forth.
-
{{cssxref("background-color")}}
-
The text's background color.
-
{{cssxref("text-shadow")}}
-
Configures a shadow effect to apply to text. Among the options for the shadow is the shadow's base color (which is then blurred and blended with the background based on the other parameters). See {{SectionOnPage("/en-US/docs/Learn/CSS/Styling_text/Fundamentals", "Text drop shadows")}} to learn more.
-
{{cssxref("text-decoration-color")}}
-
By default, text decorations (such as underlines, strikethroughs, etc) use the color property as their colors. However, you can override that behavior and use a different color for them with the text-decoration-color property.
-
{{cssxref("text-emphasis-color")}}
-
The color to use when drawing emphasis symbols adjacent to each character in the text. This is used primarily when drawing text for East Asian languages.
-
{{cssxref("caret-color")}}
-
The color to use when drawing the {{Glossary("caret")}} (sometimes referred to as the text input cursor) within the element. This is only useful in elements that are editable, such as {{HTMLElement("input")}} and {{HTMLElement("textarea")}} or elements whose HTML {{htmlattrxref("contenteditable")}} attribute is set.
-
- -

Boxes

- -

Every element is a box with some sort of content, and has a background and a border in addition to whatever contents the box may have.

- -
-
{{anch("Borders")}}
-
See the section {{anch("Borders")}} for a list of the CSS properties you can use to set the colors of a box's borders.
-
{{cssxref("background-color")}}
-
The background color to use in areas of the element that have no foreground content.
-
{{cssxref("column-rule-color")}}
-
The color to use when drawing the line separating columns of text.
-
{{cssxref("outline-color")}}
-
The color to use when drawing an outline around the outside of the element. This outline is different from the border in that it doesn't get space set aside for it in the document (so it may overlap other content). It's generally used as a focus indicator, to show which element will receive input events.
-
- -

Borders

- -

Any element can have a border drawn around it. A basic element border is a line drawn around the edges of the element's content. See {{SectionOnPage("/en-US/docs/Learn/CSS/Introduction_to_CSS/Box_model", "Box properties")}} to learn about the relationship between elements and their borders, and the article Styling borders using CSS to learn more about applying styles to borders.

- -

You can use the {{cssxref("border")}} shorthand property, which lets you configure everything about the border in one shot (including non-color features of borders, such as its width, style (solid, dashed, etc.), and so forth.

- -
-
{{cssxref("border-color")}}
-
Specifies a single color to use for every side of the element's border.
-
{{cssxref("border-left-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-top-color")}}, and {{cssxref("border-bottom-color")}}
-
Lets you set the color of the corresponding side of the element's border.
-
{{cssxref("border-block-start-color")}} and {{cssxref("border-block-end-color")}}
-
With these, you can set the color used to draw the borders which are closest to the start and end of the block the border surrounds. In a left-to-right writing mode (such as the way English is written), the block start border is the top edge and the block end is the bottom. This differs from the inline start and end, which are the left and right edges (corresponding to where each line of text in the box begins and ends).
-
{{cssxref("border-inline-start-color")}} and {{cssxref("border-inline-end-color")}}
-
These let you color the edges of the border closest to to the beginning and the end of the start of lines of text within the box. Which side this is will vary depending on the {{cssxref("writing-mode")}}, {{cssxref("direction")}}, and {{cssxref("text-orientation")}} properties, which are typically (but not always) used to adjust text directionality based on the language being displayed. For example, if the box's text is being rendered right-to-left, then the border-inline-start-color is applied to the right side of the border.
-
- -

Other ways to use color

- -

CSS isn't the only web technology that supports color. There are graphics technologies that are available on the web which also support color.

- -
-
The HTML Canvas API
-
Lets you draw 2D bitmapped graphics in a {{HTMLElement("canvas")}} element. See our Canvas tutorial to learn more.
-
SVG (Scalable Vector Graphics)
-
Lets you draw images using commands that draw specific shapes, patterns, and lines to produce an image. SVG commands are formatted as XML, and can be embedded directly into a web page or can be placed in he page using the {{HTMLElement("img")}} element, just like any other type of image.
-
WebGL
-
The Web Graphics Library is an OpenGL ES-based API for drawing high-performance 2D and 3D graphics on the Web. See Learn WebGL for 2D and 3D graphics to find out more.
-
- -

How to describe a color

- -

In order to represent a color in CSS, you have to find a way to translate the analog concept of "color" into a digital form that a computer can use. This is typically done by breaking down the color into components, such as how much of each of a set of primary colors to mix together, or how bright to make the color. As such, there are several ways you can describe color in CSS.

- -

For more detailed discussion of each of the color value types, see the reference for the CSS {{cssxref("<color>")}} unit.

- -

Keywords

- -

A set of standard color names have been defined, letting you use these keywords instead of numeric representations of colors if you choose to do so and there's a keyword representing the exact color you want to use. Color keywords include the standard primary and secondary colors (such as red, blue, or orange), shades of gray (from black to white, including colors like darkgray and lightgrey), and a variety of other blended colors including lightseagreen, cornflowerblue, and rebeccapurple.

- -

See {{SectionOnPage("/en-US/docs/Web/CSS/color_value", "Color keywords", "code")}} for a list of all available color keywords.

- -

RGB values

- -

There are three ways to represent an RGB color in CSS.

- -

Hexadecimal string notation

- -

Hexadecimal string notation represents a color using hexadecimal digits to represent each of the color components (red, green, and blue). It may also include a fourth component: the alpha channel (or opacity). Each color component can be represented as a number between 0 and 255 (0x00 and 0xFF) or, optionally, as a number between 0 and 15 (0x0 and 0xF). All components must be specified using the same number of digits. If you use the single-digit notation, the final color is computed by using each component's digit twice; that is, "#D" becomes "#DD" when drawing.

- -

A color in hexadecimal string notation always begins with the character "#". After that come the hexadecimal digits of the color code. The string is case-insensitive.

- -
-
"#rrggbb"
-
Specifies a fully-opaque color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
-
"#rrggbbaa"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
-
"#rgb"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
-
"#rgba"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
-
- -

As an example, you can represent the opaque color bright blue as "#0000ff" or "#00f". To make it 25% opaque, you can use "#0000ff44" or "#00f4".

- -

RGB functional notation

- -

RGB (Red/Green/Blue) functional notation, like hexadecimal string notation, represents colors using their red, green, and blue components (as well as, optionally, an alpha channel component for opacity). However, instead of using a string, the color is defined using the CSS function {{cssxref("color_value", "rgb()", "#rgb()")}}. This function accepts as its input parameters the values of the red, green, and blue components and an optional fourth parameter, the value for the alpha channel.

- -

Legal values for each of these parameters are:

- -
-
red, green, and blue
-
Each must be an {{cssxref("<integer>")}} value between 0 and 255 (inclusive), or a {{cssxref("<percentage>")}} from 0% to 100%.
-
alpha
-
The alpha channel is a number between 0.0 (fully transparent) and 1.0 (fully opaque). You can also specify a percentage where 0% is the same as 0.0 and 100% is the same as 1.0.
-
- -

For example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%).

- -

HSL functional notation

- -

Designers and artists often prefer to work using the {{interwiki("wikipedia", "HSL and HSV", "HSL")}} (Hue/Saturation/Luminosity) color method. On the web, HSL colors are represented using HSL functional notation. The hsl() CSS function is very similar to the rgb() function in usage otherwise.

- -
-
HSL color cylinder -
Figure 1. An HSL color cylinder. Hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. Saturation is a percentage of how much of the way between being a shade of gray and having the maximum possible amount of the given hue. As the value of luminance (or lightness) increases, the color transitions from the darkest possible to the brightest possible (from black to white). Image courtesy of user SharkD on Wikipedia, distributed under the CC BY-SA 3.0 license.
-
-
- -

The value of the hue (H) component of an HSL color is an angle from red around through yellow, green, cyan, blue, and magenta (ending up back at red again at 360°) that identifies what the base color is. The value can be specified in any {{cssxref("<angle>")}} unit supported by CSS, including degrees (deg), radians (rad), gradians (grad), or turns (turn). But this doesn't control how vivid or dull, or how bright or dark the color is.

- -

The saturation (S) component of the color specifies what percentage of the final color is comprised of the specified hue. The rest is defined by the grey level provided by the luminance (L) component.

- -

Think of it like creating the perfect paint color:

- -
    -
  1. You start with base paint that's the maximum intensity possible for a given color, such as  the most intense blue that can be represented by the user's screen. This is the hue (H) component: a value representing the angle around the color wheel for the vivid hue we want to use as our base.
  2. -
  3. Then select a greyscale paint that corresponds how bright you want the color to be; this is the luminance. Do you want it to be very bright and nearly white, or very dark and closer to black, or somewhere in between? This is specified using a percentage, where 0% is perfectly black and 100% is perfectly white. (regardless of the saturation or hue). In between values are a literal grey area.
  4. -
  5. Now that you have a grey paint and a perfectly vivid color, you need to mix them together. The saturation (S) component of the color indicates what percentage of the final color should be comprised of that perfectly vivid color. The rest of the final color is made up of the grey paint that represents the saturation.
  6. -
- -

You can also optionally include an alpha channel, to make the color less than 100% opaque.

- -

Here are some sample colors in HSL notation:

- -
- - -

{{EmbedLiveSample("hsl-swatches", 300, 260)}}

-
- -
-

Note that when you omit the hue's unit, it's assumed to be in degrees (deg).

-
- -

Using color

- -

Now that you know what CSS properties exist that let you apply color to elements and the formats you can use to describe colors, you can put this together to begin to make use of color. As you may have seen from the list under {{anch("Things that can have color")}}, there are plenty of things you can color with CSS. Let's look at this from two sides: using color within a {{Glossary("stylesheet")}}, and adding and changing color using {{Glossary("JavaScript")}} code to alter the styles of elements.

- -

Specifying colors in stylesheets

- -

The easiest way to apply color to elements—and the way you'll usually do it—is to simply specify colors in the CSS that's used when rendering elements. While we won't use every single property mentioned previously, we'll look at a couple of examples. The concept is the same anywhere you use color.

- -

Let's take a look at an example, starting by looking at the results we're trying to achieve:

- -
{{EmbedLiveSample("Specifying_colors_in_stylesheets", 650, 150)}}
- -

HTML

- -

The HTML responsible for creating the above example is shown here:

- -
<div class="wrapper">
-  <div class="box boxLeft">
-    <p>
-      This is the first box.
-    </p>
-  </div>
-  <div class="box boxRight">
-    <p>
-      This is the second box.
-    </p>
-  </div>
-</div>
- -

This is pretty simple, using a {{HTMLElement("div")}} as a wrapper around the contents, which consists of two more <div>s, each styled differently with a single paragraph ({{HTMLElement("p")}}) in each box.

- -

The magic happens, as usual, in the CSS, where we'll apply colors define the layout for the HTML above.

- -

CSS

- -

We'll look at the CSS to create the above results a piece at a time, so we can review the interesting parts one by one.

- -
.wrapper {
-  width: 620px;
-  height: 110px;
-  margin: 0;
-  padding: 10px;
-  border: 6px solid mediumturquoise;
-}
- -

The .wrapper class is used to assign styles to the {{HTMLElement("div")}} that encloses all of our other content. This establishes thesize of the container using {{cssxref("width")}} and {{cssxref("height")}} as well as its {{cssxref("margin")}} and {{cssxref("padding")}}.

- -

Of more interest to our discussion here is the use of the {{cssxref("border")}} property to establish a border around the outside edge of the element. This border is a solid line, 6 pixels wide, in the color mediumturquoise.

- -

Our two colored boxes share a number of properties in common, so next we establish a class, .box, that defines those shared properties:

- -
.box {
-  width: 290px;
-  height: 100px;
-  margin: 0;
-  padding: 4px 6px;
-  font: 28px "Marker Felt", "Zapfino", cursive;
-  display: flex;
-  justify-content: center;
-  align-items: center;
-}
- -

In brief, .box establishes the size of each box, as well as the configuration of the font used within. We also take advantage of CSS Flexbox to easily center the contents of each box. We enable flex mode using {{cssxref("display", "display: flex")}}, and set both {{cssxref("justify-content")}} and {{cssxref("align-items")}} to center. Then we can create a class for each of the two boxes that defines the propeties that differ between the two.

- -
.boxLeft {
-  float: left;
-  background-color: rgb(245, 130, 130);
-  outline: 2px solid darkred;
-}
- -

The .boxLeft class—which, cleverly, is used to style the box on the left—floats the box to the left, then sets up the colors:

- - - -
.boxRight {
-  float: right;
-  background-color: hsl(270deg, 50%, 75%);
-  outline: 4px dashed rgb(110, 20, 120);
-  color: hsl(0deg, 100%, 100%);
-  text-decoration: underline wavy #88ff88;
-  text-shadow: 2px 2px 3px black;
-}
- -

Finally, the .boxRight class describes the unique properties of the box that's drawn on the right. It's configured to float the box to the right so that it appears next to the previous box. Then the following colors are established:

- - - -

Letting the user pick a color

- -

There are many situations in which your web site may need to let the user select a color. Perhaps you have a customizable user interface, or you're implementing a drawing app. Maybe you have editable text and need to let the user choose the text color. Or perhaps your app lets the user assign colors to folders or items. Although historically it's been necessary to implement your own {{interwiki("wikipedia", "color picker")}}, HTML now provides support for browsers to provide one for your use through the {{HTMLElement("input")}} element, by using "color" as the value of its {{htmlattrxref("type", "input")}} attribute.

- -

The <input> element represents a color only in the {{anch("Hexadecimal string notation", "hexadecimal string notation")}} covered above.

- -

Example: Picking a color

- -

Let's look at a simple example, in which the user can choose a color. As the user adjusts the color, the border around the example changes to reflect the new color. After finishing up and picking the final color, the color picker's value is displayed.

- -

{{EmbedLiveSample("Example_Picking_a_color", 525, 275)}}

- -
-

On macOS, you indicate that you've finalized selection of the color by closing the color picker window.

-
- -

HTML

- -

The HTML here creates a box that contains a color picker control (with a label created using the {{HTMLElement("label")}} element) and an empty paragraph element ({{HTMLElement("p")}}) into which we'll output some text from our JavaScript code.

- -
<div id="box">
-  <label for="colorPicker">Border color:</label>
-  <input type="color" value="#8888ff" id="colorPicker">
-  <p id="output"></p>
-</div>
- -

CSS

- -

The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won't last, courtesy of the JavaScript below...

- -
#box {
-  width: 500px;
-  height: 200px;
-  border: 2px solid rgb(245, 220, 225);
-  padding: 4px 6px;
-  font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"
-}
- -

JavaScript

- -

The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element.

- -
let colorPicker = document.getElementById("colorPicker");
-let box = document.getElementById("box");
-let output = document.getElementById("output");
-
-box.style.borderColor = colorPicker.value;
-
-colorPicker.addEventListener("input", function(event) {
-  box.style.borderColor = event.target.value;
-}, false);
-
-colorPicker.addEventListener("change", function(event) {
-  output.innerText = "Color set to " + colorPicker.value + ".";
-}, false);
- -

The {{event("input")}} event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker. Each time this event arrives, we set the box's border color to match the color picker's current value.

- -

The {{event("change")}} event is received when the color picker's value is finalized. We respond by setting the contents of the <p> element with the ID "output" to a string describing the finally selected color.

- -

Using color wisely

- -

Making the right choices when selecting colors when designing a web site can be a tricky process, especially if you aren't well-grounded in art, design, or at least basic color theory. The wrong color choice can render your site unattractive, or even worse, leave the content unreadable due to problems with contrast or conflicting colors. Worse still, if using the wrong colors can result in your content being outright unusable by people withcertain vision problems, particularly color blindness.

- -

Finding the right colors

- -

Coming up with just the right colors can be tricky, especially without training in art or design. Fortunately, there are tools available that can help you. While they can't replace having a good designer helping you make these decisions, they can definitely get you started.

- -

Base color

- -

The first step is to choose your base color. This is the color that in some way defines your web site or the subject matter of the site. Just as we associate green with the beverage {{interwiki("wikipedia", "Mountain Dew")}} and one might think of the color blue in relationship with the sky or the ocean, choosing an appropriate base color to represent your site is a good place to start. There are plenty of ways to select a base color; a few ideas include:

- - - -

When trying to decide upon a base color, you may find that browser extensions that let you select colors from web content can be particularly handy. Some of these are even specifically designed to help with this sort of work. For example, the web site ColorZilla offers an extension (Chrome / Firefox) that offers an eyedropper tool for picking colors from the web. It can also take averages of the colors of pixels in various sized areas or even a selected area of the page.

- -
-

The advantage to averaging colors can be that often what looks like a solid color is actually a surprisingly varied number of related colors all used in concert, blending to create a desired effect. Picking just one of these pixels can result in getting a color that on its own looks very out of place.

-
- -

Fleshing out the palette

- -

Once you have decided on your base color, there are plenty of online tools that can help you build out a palette of appropriate colors to use along with your base color by applying color theory to your base color to determine appropriate added colors. Many of these tools also support viewing the colors filtered so you can see what they would look like to people with various forms of color blindness. See {{anch("Color and accessibility")}} for a brief explanation of why this matters.

- -

A few examples (all free to use as of the time this list was last revised):

- - - -

When designing your palette, be sure to keep in mind that in addition to the colors these tools typically generate, you'll probably also need to add some core neutral colors such as white (or nearly white), black (or nearly black), and some number of shades of gray.

- -
-

Usually, you are far better off using the smallest number of colors possible. By using color to accentuate rather than adding color to everything on the page, you keep your content easy to read and the colors you do use have far more impact.

-
- -

Color theory resources

- -

A full review of color theory is beyond the scope of this article, but there are plenty of articles about color theory available, as well as courses you can find at nearby schools and universities. A couple of useful resources about color theory:

- -
-
Color Science (Khan Academy in association with Pixar)
-
An online course which introduces concepts such as what color is, how it's percieved, and how to use colors to express ideas. Presented by Pixar artists and designers.
-
{{interwiki("wikipedia", "Color theory")}} on Wikipedia
-
Wikipedia's entry on color theory, which has a lot of great information from a technical perspective. It's not really a resource for helping you with the color sleection process, but is still full of useful information.
-
- -

Color and accessibility

- -

There are several ways color can be an {{Glossary("accessibility")}} problem. Improper or careless use of color can result in a web site or app that a percentage of your target audience may not be able to use adequately, resulting in lost traffic, lost business, and possibly even a public relations problem. So it's important to consider your use of color carefully.

- -

You should do at least basic research into {{interwiki("wikipedia", "color blindness")}}. There are several kinds; the most common is red-green color blindness, which causes people to be unable to differentiate between the colors red and green. There are others, too, ranging from inabilities to tell the difference between certain colors to total inability to see color at all.

- -
-

The most important rule: never use color as the only way to know something. If, for example, you indicate success or failure of an operation by changing the color of a shape from white to green for success and red for failure, users with red-green color-blindness won't be able to use your site properly. Instead, perhaps use both text and color together, so that everyone can understand what's happening.

-
- -

For more information about color blindness, see the following articles:

- - - -

Palette design example

- -

Let's consider a quick example of selecting an appropriate color palette for a site. Imagine that you're building a web site for a new game that takes place on the planet Mars. So let's do a Google search for photos of Mars. Lots of good examples of Martian coloration there. We carefully avoid the mockups and the photos from movies. And we decide to use a photo taken by one of the Mars landers humanity has parked on the surface over the last few decades, since the game takes place on the planet's surface. We use a color picker tool to select a sample of the color we choose.

- -

Using an eyedropper tool, we identify a color we like and determine that the color in question is #D79C7A, which is an appropriate rusty orange-red color that's so stereotypical of the Martian surface.

- -

Having selected our base color, we need to build out our palette. We decide to use Paletton to come up with the other colors we need. Upon opening Paletton, we see:

- -

Right after loading Paletton.

- -

Next, we enter our color's hex code (D79C7A) into the "Base RGB" box at the bottom-left corner of the tool:

- -

After entering base color

- -

We now see a monochromatic palette based on the color we picked from the Mars photo. If you need a lot of related colors for some reason, those are likely to be good ones. But what we really want is an accent color. Something that will pop along side the base color. To find that, we click the "add complementary" toggle underneath the menu that lets you select the palette type (currently "Monochromatic"). Paletton computes an appropriate accent color; clicking on the accent color down in the bottom-right corner tells us that this color is #508D7C.

- -

Now with complementary colors included.

- -

If you're unhappy with the color that's proposed to you, you can change the color scheme, to see if you find something you like better. For example, if we don't like the proposed greenish-blue color, we can click the Triad color scheme icon, which presents us with the following:

- -

Triad color scheme selected

- -

That greyish blue in the top-right looks pretty good. Clicking on it, we find that it's #556E8D. That would be used as the accent color, to be used sparingly to make things stand out, such as in headlines or in the highlighting of tabs or other indicators on the site:

- -

Triad color scheme selected

- -

Now we have our base color and our accent. On top of that, we have a few complementary shades of each, just in case we need them for gradients and the like. The colors can then be exported in a number of formats so you can make use of them.

- -

Once you have these colors, you will probably still need to select appropriate neutral colors. Common design practice is to try to find the sweet spot where there's just enough contrast that the text is crisp and readable but not enough contrast to become harsh for the eyes. It's easy to go too far in one way or another so be sure to get feedback on your colors once you've selected them and have examples of them in use available. If the contrast is too low, your text will tend to be washed out by the background, leaving it unreadable, but if your contrast is too high, the user may find your site garish and unpleasant to look at.

- -

Color, backgrounds, contrast, and printing

- -

What looks good on screen may look very different on paper. In addition, ink can be expensive, and if a user is printing your page, they don't necessarily need all the backgrounds and such using up their precious ink when all that matters is the text itself. Most browsers, by default, remove background images when printing documents.

- -

If your background colors and images have been selected carefully and/or are crucial to the usefulness of the content, you can use the CSS {{cssxref("color-adjust")}} property to tell the browser that it should not make adjustments to the appearance of content.

- -

The default value of color-adjust, economy, indicates that the browser is allowed to make appearance changes as it deems necessary in order to try to optimize the legibility and/or print economy of the content, given the type of output device the document is being drawn onto.

- -

You can set color-adjust to exact to tell the browser that the element or elements on which you use it have been designed specifically to best work with the colors and images left as they are. With this set, the browser won't tamper with the appearance of the element, and will draw it as indicated by your CSS.

- -
-

Note: There is no guarantee, though, that color-adjust: exact will result in your CSS being used exactly as given. If the browser provides user preferences to change the output (such as a "don't print backgrounds" checkbox in a print dialog box), that overrides the value of color-adjust.

-
- -

See also

- - 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")}}

diff --git "a/files/fa/web/\330\254\330\247\331\210\330\247\330\247\330\263\332\251\330\261\333\214\331\276\330\252/index.html" "b/files/fa/web/\330\254\330\247\331\210\330\247\330\247\330\263\332\251\330\261\333\214\331\276\330\252/index.html" deleted file mode 100644 index 1de3deb24e..0000000000 --- "a/files/fa/web/\330\254\330\247\331\210\330\247\330\247\330\263\332\251\330\261\333\214\331\276\330\252/index.html" +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: جاوااسکریپت -slug: Web/جاوااسکریپت -tags: - - JavaScript - - Landing - - NeedsTranslation - - TopicStub ---- -
یک معرفی مجدد برای جاوااسکریپت
-یک بررسی کلی برا آن‌هایی که فکر می‌کنند در مورد جاوااسکریپت می‌دانند
- -

{{JsSidebar}}

- -

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

- -

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

- -

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

- -

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

- -
-
-

مستندات

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

مقالات معرفی

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

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

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

مقالات دیگر

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

View All...

-
- -
-

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

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

نمایش همه...

- -

دیگر منابع

- -
-
JavaScript Garden
-
سایتی با اطلاعات مفید در مورد قطعات داخلی‌تر جاوااسکریپت.
-
JSWiki
-
یک ویکی مبتنی بر Githubکه منابع و کتابخانه‌ها را ایندکس گذاری کرده است.
-
Stack Overflow
-
یک سایت همکاری ساخته و نگه‌داری شده Q&A و می‌توانید برای جواب سوال خودرا در آن جستجو کنید. اگر جواب سوال خودرا پیدا نکردید می‌توانید سوال خودرا در آن‌جا مطرح کنید.
-
Pineapple · JavaScript
-
یک پایگاه داده بزرگ از آموزش و منابع حال حاضر جاوااسکریپت.
-
Life of JavaScript
-
منابع عالی در مورد جاوااسکریپت شامل کتاب، ارایه‌ها، فیلم‌ها، فیدها، سایت‌ها، کتابخانه‌ها، محیط‌های کاری، ابزارها که در یک‌جا جمع آموری شده است.
-
- - - - -
-
- -

‎‎*‎JavaScript is a trademark or registered trademark of Oracle in the U.S. and other countries‎‎.‎

-- cgit v1.2.3-54-g00ecf