From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../ar/web/javascript/about_javascript/index.html | 61 ++ .../control_flow_and_error_handling/index.html | 467 ++++++++++++ .../javascript/guide/grammar_and_types/index.html | 680 +++++++++++++++++ files/ar/web/javascript/guide/index.html | 116 +++ .../web/javascript/guide/introduction/index.html | 159 ++++ .../guide/loops_and_iteration/index.html | 352 +++++++++ .../guide/regular_expressions/index.html | 813 +++++++++++++++++++++ .../guide/working_with_objects/index.html | 516 +++++++++++++ .../index.html" | 698 ++++++++++++++++++ files/ar/web/javascript/index.html | 121 +++ .../index.html | 423 +++++++++++ .../reference/classes/constructor/index.html | 132 ++++ .../ar/web/javascript/reference/classes/index.html | 380 ++++++++++ .../ar/web/javascript/reference/errors/index.html | 31 + .../reference/errors/unexpected_type/index.html | 68 ++ .../reference/global_objects/array/index.html | 481 ++++++++++++ .../global_objects/array/isarray/index.html | 146 ++++ .../reference/global_objects/array/join/index.html | 143 ++++ .../reference/global_objects/array/pop/index.html | 134 ++++ .../global_objects/array/reverse/index.html | 124 ++++ .../global_objects/array/slice/index.html | 151 ++++ .../global_objects/date/getdate/index.html | 85 +++ .../reference/global_objects/date/index.html | 261 +++++++ .../reference/global_objects/date/now/index.html | 80 ++ .../reference/global_objects/date/parse/index.html | 182 +++++ .../global_objects/date/setdate/index.html | 95 +++ .../reference/global_objects/date/utc/index.html | 133 ++++ .../global_objects/function/call/index.html | 219 ++++++ .../reference/global_objects/function/index.html | 183 +++++ .../javascript/reference/global_objects/index.html | 126 ++++ .../reference/global_objects/json/index.html | 215 ++++++ .../reference/global_objects/map/index.html | 358 +++++++++ .../reference/global_objects/math/index.html | 190 +++++ .../global_objects/object/constructor/index.html | 152 ++++ .../reference/global_objects/object/index.html | 182 +++++ .../reference/global_objects/string/index.html | 314 ++++++++ .../global_objects/string/startswith/index.html | 101 +++ .../index.html" | 12 + files/ar/web/javascript/reference/index.html | 50 ++ .../operators/destructuring_assignment/index.html | 428 +++++++++++ .../web/javascript/reference/operators/index.html | 302 ++++++++ .../javascript/reference/operators/new/index.html | 178 +++++ .../operators/object_initializer/index.html | 403 ++++++++++ .../operators/operator_precedence/index.html | 420 +++++++++++ .../javascript/reference/operators/this/index.html | 381 ++++++++++ .../web/javascript/reference/statements/index.html | 141 ++++ .../reference/statements/return/index.html | 145 ++++ .../get/index.html" | 165 +++++ .../index.html" | 645 ++++++++++++++++ 49 files changed, 12342 insertions(+) create mode 100644 files/ar/web/javascript/about_javascript/index.html create mode 100644 files/ar/web/javascript/guide/control_flow_and_error_handling/index.html create mode 100644 files/ar/web/javascript/guide/grammar_and_types/index.html create mode 100644 files/ar/web/javascript/guide/index.html create mode 100644 files/ar/web/javascript/guide/introduction/index.html create mode 100644 files/ar/web/javascript/guide/loops_and_iteration/index.html create mode 100644 files/ar/web/javascript/guide/regular_expressions/index.html create mode 100644 files/ar/web/javascript/guide/working_with_objects/index.html create mode 100644 "files/ar/web/javascript/guide/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" create mode 100644 files/ar/web/javascript/index.html create mode 100644 files/ar/web/javascript/introduction_to_object-oriented_javascript/index.html create mode 100644 files/ar/web/javascript/reference/classes/constructor/index.html create mode 100644 files/ar/web/javascript/reference/classes/index.html create mode 100644 files/ar/web/javascript/reference/errors/index.html create mode 100644 files/ar/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/parse/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/setdate/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/function/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/json/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/map/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/math/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/object/constructor/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/object/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/string/index.html create mode 100644 files/ar/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 "files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" create mode 100644 files/ar/web/javascript/reference/index.html create mode 100644 files/ar/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/ar/web/javascript/reference/operators/index.html create mode 100644 files/ar/web/javascript/reference/operators/new/index.html create mode 100644 files/ar/web/javascript/reference/operators/object_initializer/index.html create mode 100644 files/ar/web/javascript/reference/operators/operator_precedence/index.html create mode 100644 files/ar/web/javascript/reference/operators/this/index.html create mode 100644 files/ar/web/javascript/reference/statements/index.html create mode 100644 files/ar/web/javascript/reference/statements/return/index.html create mode 100644 "files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/get/index.html" create mode 100644 "files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" (limited to 'files/ar/web/javascript') diff --git a/files/ar/web/javascript/about_javascript/index.html b/files/ar/web/javascript/about_javascript/index.html new file mode 100644 index 0000000000..4a6fa9739e --- /dev/null +++ b/files/ar/web/javascript/about_javascript/index.html @@ -0,0 +1,61 @@ +--- +title: About JavaScript +slug: Web/JavaScript/About_JavaScript +tags: + - جافا سكريبت + - مبتدئ + - مقدمة +translation_of: Web/JavaScript/About_JavaScript +--- +
{{JsSidebar}}
+ +

ماهي جافا سكريبت

+ +

جافا سكريبت® (غالبا ما تختصر بـ JS) هي لغة خفيفة الوزن، مفسّرة، كائنية التوجه مع دوال من الدرجة الأولى، وهي معروفة باسم لغة البرمجة النصية لصفحات الويب، ولكنها تستخدم في العديد من البيئات غير المتصفّح أيضًا. وهي لغة برمجة مبنية على نماذج أولية ومتعددة النماذج تتسم بالديناميكية و تدعم أنماط البرمجة الكائنية التوجه و اﻷساسية و الوظيفية.

+ +

تعمل جافا سكريبت على جانب العميل\المستخدم من الويب، و التي يمكن إستخدامها لتصميم\برمجة كيفية تصرف صفحات الويب عند وقوع خطأ ما. جافا سكريبت هي لغة سهلة التعلم ولغة برمجة قوية ، و تستخدم على نطاق واسع للتحكم في سلوك صفحات الويب.

+ +

على عكس الاعتقاد الخاطئ الشائع ، فإن جافا سكريبت ليست "جافا المفسرة". باختصار ، جافا سكريبت هي لغة برمجة ديناميكية تدعم بناء الكائن المعتمد على النماذج. التركيب اﻷساسي مشابه -بشكل مقصود- لجافا و سي++ لتقليل عدد المفاهيم الجديدة المطلوبة لتعلم اللغة. إن تركيبات اللغة مثل عبارات if و حلقات for و while ، و الكتل switch and try ... catch تعمل بالمثل كما في هذه اللغات (أو أقرب إلى ذلك)

+ +

يمكن أن تعمل جافا سكريبت كلغة إجرائية و لغة كائنية التوجه.. يتم إنشاء الكائنات برمجياً في جافا سكريبت ، عن طريق إرفاق طرق وخصائص الكائنات الفارغة الأخرى في وقت التشغيل، على عكس التركيب\البناء اللغوي لتعريفات الأصناف الشائعة في اللغات المترجمة أمثال سي++ و جافا. بمجرد إنشاء كائن، يمكن استخدامه كمخطط (أو نموذج أولي) لإنشاء كائنات مشابهة.

+ +

تتضمن الإمكانات الديناميكية لجافا سكريبت بناء الكائن وقت التشغيل ، وقوائم المعاملات المتغيرة ، ومتغيرات الوظيفة ، وإنشاء النص البرمجي الديناميكي (عن طريق eval) ، واستبطان الكائن (عن طريق for ... in)، واستعادة الكود المصدري (يمكن لبرامج جافا سكريبت تفكيك هيئات\أجسام الوظائف رجوعا إلى نصها المصدري).

+ +

لإجراء مناقشة أكثر عمقاً لبرمجة جافا سكريبت ، تابع روابط موارد جافا سكريبت أدناه.

+ +

ما هي تطبيقات جافا سكريبت المتاحة؟

+ +

The Mozilla project provides two JavaScript implementations. The first ever JavaScript was created by Brendan Eich at Netscape, and has since been updated to conform to ECMA-262 Edition 5 and later versions. This engine, code named SpiderMonkey, is implemented in C/C++. The Rhino engine, created primarily by Norris Boyd (also at Netscape) is a JavaScript implementation written in Java. Like SpiderMonkey, Rhino is ECMA-262 Edition 5 compliant.

+ +

Several major runtime optimizations such as TraceMonkey (Firefox 3.5), JägerMonkey (Firefox 4) and IonMonkey were added to the SpiderMonkey JavaScript engine over time. Work is always ongoing to improve JavaScript execution performance.

+ +

Besides the above implementations, there are other popular JavaScript engines such as:-

+ + + +

Each of Mozilla's JavaScript engines expose a public API which application developers can use to integrate JavaScript into their software. By far, the most common host environment for JavaScript is web browsers. Web browsers typically use the public API to create host objects responsible for reflecting the DOM into JavaScript.

+ +

Another common application for JavaScript is as a (Web) server side scripting language. A JavaScript web server would expose host objects representing a HTTP request and response objects, which could then be manipulated by a JavaScript program to dynamically generate web pages. Node.js is a popular example of this.

+ +

مصادر جافا سكريبت

+ +
+
SpiderMonkey
+
Information specific to Mozilla's implementation of JavaScript in C/C++ engine (aka SpiderMonkey), including how to embed it in applications.
+
+ +
+
Rhino
+
Information specific to the JavaScript implementation written in Java (aka Rhino).
+
Language resources
+
Pointers to published JavaScript standards.
+
A re-introduction to JavaScript
+
JavaScript guide and JavaScript reference.
+
+ +

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

diff --git a/files/ar/web/javascript/guide/control_flow_and_error_handling/index.html b/files/ar/web/javascript/guide/control_flow_and_error_handling/index.html new file mode 100644 index 0000000000..d87ef2f7e9 --- /dev/null +++ b/files/ar/web/javascript/guide/control_flow_and_error_handling/index.html @@ -0,0 +1,467 @@ +--- +title: التحكم فى التدفق وامساك الاخطاء +slug: Web/JavaScript/Guide/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")}}
+ +

جافاسكريبت تدعم مجموعة من البيانات المدمجة، وتحديدا التحكم في تدفق البيانات، التي يمكنك استخدامها لخلق قدرا كبيرا من التفاعل في التطبيق الخاص بك. يقدم هذا الفصل لمحة عامة عن هذه البيانات.

+ +
+

يحتوي هذا الفصل، مرجع الجافاسكريبت على تفاصيل شاملة عن التعليمات البرمجية. في جافاسكريبت، يتم استخدام رمز الفاصلة المنقوطة (;) لانهاء التعليمات البرمجية.

+ +
+

ملحوظة: برامج الجافاسكريبت وبيانات الجافاسكريبت، غالباً ما تسمى تعليمات برمجية.

+
+ +

أي تعبير جافا سكريبت، هو  أيضا تعليمة برمجية. راجع Expressions and operators  للحصول على معلومات كاملة حول التعبيرات.

+ +

Block statement

+ +

ابسط تعليمة برمجية هي التعليمة البرمجية بلوك  block، التي تستخدم لاحتواء مجموعة من التعليمات البرمجية. البلوك محدد بواسطة الاقواس المتعرجة:

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

مثال

+ +

اغلب استخدامات البلوك، تكون مع تعليمات التحكم في التدفق ( مثل if, for, while )

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

لدينا هنا، { ;++x } التعليمة البرمجة block.

+ +

هام: في جافا سكريبت قبل ECMAScript2015. البلوك لم يكن لديه نطاق. المتغيرات المستخدمة في البلوك، سيتم تغيير نطاقها الى النطاق العام وهو السكريبت، فتصبح متغيرات عامة متاحة لجميع التعليمات البرمجية في السكريبت، اما اذا وجد البلوك داخل دالة سيتم تغيير نطاقها لهذه الدالة، وبالتالي ستصبح متغيرات محلية متاحة لهذه الدالة فقط.

+ +

في جافا سكريبت، البلوكات "المستقلة"  يمكن أن ينتج  عنها نتائج مختلفة تماما عما كان سينتج في C أو جافا. فمثلا

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

مخرجات التعليمة البرمجية اعلاه، ستكون 2 وذالك لان المتغير x المتواجد داخل البلوك والمتغير x المتواجد خارج البلوك لديهما نفس النطاق، او بمعنى اصح، كلاهما في النطاق العام وهو السكريببت. في C أو جافا. المخرجات ستكون 1.

+ +

ابتداءا من ECMAScript2015. استخدام المتغير let داخل البلوك سينتج عنه سلوك مغاير. راجع {{jsxref("Statements/let", "let")}} صفحة المرجع للحصول على مزيد من المعلومات.

+ +

التعليمات الشرطية

+ +

التعليمة الشرطية هي مجموعة من الأوامر التي ستنفذ إذا تحقق شرطا معيناً. تدعم الجافاسكريبت اثنين من التعليمات الشرطية: هما if...else و switch.

+ +

التعليمة if...else

+ +

ستنفذ التعليمة البرمجية المرتبطة بالتعليمة if اذا كان الشرط المنطقي يساوي true. وكذالك ستنفذ التعليمة البرمجية المرتبطة بالتعليمة else اذا كان الشرط المنطقي يساوي false. استخدام التعليمة else اختياري. فيما تكون التعليمة if على الشكل التالي،

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

الشرط condition، يمكن ان يكون اي تعبير لإختبار ما اذا كان الشرط true او false راجع Boolean. لتوضيح ما الذي سيتم تنفيذه: في حالة ما اذا كان الشرط صحيح  سيتم تنفيذ statement_1، اما اذا كان الشرط غير صحيح سيتم تنفيذ statement_2، يمكن ل statement_1 و statement_2 ان تكون اي تعليمات برمجية، بما فيها تعليمة if اخرى.

+ +

يمكنك أيضا توسيع مجال التعليمات الشرطية باستخدام else if لاختبار شروط متعددة في تسلسل، كما يلي:

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

في حالة وجود شروط متعددة سيتم تنفيذ شرط واحد فقط، وهو الشرط المنطقي الذي سيتم اختباره ب true. لتنفيذ عدة تعليمات برمجية، قم بتضمينها في التعليمة بلوك ({ ... }). من الجيد دائماً استخدام التعليمة بلوك، لا سيما عند استخدام التعليمات الشرطية المتداخلة :

+ +
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;
+}
+
+ +
من المستحسن عدم استخدام التعيينات البسيطة في التعبير الشرطي، لأنه يمكن الخلط بين التعيين والمساواة، على سبيل المثال، لا تستخدم التالي:
+ +
 
+ +
if (x = y) {
+  /* statements here */
+}
+
+ +

إذا كنت بحاجة إلى استخدام تعيين بسيط في تعبير شرطي، استخدم أقواس إضافية حول التعيين. على سبيل المثال:

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

القيم  Falsy

+ +

القيم التالية تُقَيًم إلى false عند اختباها في تعليمة شرطية (وتعرف ايضا بالقيم {{Glossary("Falsy")}}):

+ + + +

كل القيم الأخرى، بما في ذلك جميع الكائنات، تقيم إلى true عندما يتم تمريرها إلى تعليمة شرطية.

+ +

لا تخلط بين القيم المنطقية الاولية true و false مع القيم true و false للكائن {{jsxref("Boolean")}}. على سبيل المثال:

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

مثال

+ +

فى المثال التالى, الدالة checkData ستعود ب true ادا كان عدد الحروف في الكائن Text يساوي ثلاثة، بخلاف ذالك، سيظهر التنبيه (alert) وتعود ب 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

+ +

التعليمة switch تسمح للبرنامج باختبار التعبير، وذالك من خلال مطابقة قيمة التعبير مع الحالة case. إذا تم العثور على تطابق، البرنامج سينفذ التعليمة البرمجية المرتبطة بها. التعليمة switch تكون على الشكل التالي:

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

بداية يقوم البرنامج بالبحث عن الحالة case التي تطابق قيمتها قيمة ال expression، اذا وجدت، يقوم البرنامج بتنفيذ التعليمة البرمجية المرتبطة بها، اذا لم يجد ما يبحث عنه في اي من الحالات case، سيقوم البرنامج بتنفيذ التعليمات البرمجية المرتبطة بالحالة default اذا وجدت، لان وجود الحالة default في التعليمة switch اختياري. اذا لم يجد البرنامج اي حالة case متطابقة ولا الحالة default سيقوم بتنفيذ التعليمات البرمجية التي تلي التعليمة switch.

+ +

التعليمة break مرتبطة مع كل حالة case، مهمتها جعل البرنامج يقفز خارج التعليمة switch بمجرد تنفيذ التعليمة البرمجية، واستكمال تنفيذ التعليمات البرمجية التي تلي التعليمة switch. بما ان وجود التعليمة break اختياري، ففي حالة عدم وجودها سيقوم البرنامج بتنفيذ التعليمة التالية في switch.

+ +

مثال

+ +

في المثال التالي، اذا كان fruittype يساوي "Bananas"،  سيقوم البرنامج بتنفيذ  التعليمات البرمجية المرتبطة بالحالة 'case: 'Banana. عندما سسيجد break، سيقوم بايقاف switch وينفذ التعليمات البرمجية التي تليها. اذا لم يجد break سينفذ التعليمة البرمجية المرتبطة بالحالة 'case: 'Cherries ايضا. 

+ +
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?");
+ +
+

ملاحظة : لمزيد من التفاصيل حول التعليمة  switch.

+
+ +

التعليمات المعالجة للاستثناءات

+ +
+

من الثابت بقواعد الرياضيات انه لا يجوز القسمة على صفر بأي حال من الأحوال لذلك لن يتمكن البرنامج من تنفيذ العملية المطلوبة وستظهر للمستخدم رسالة خطا تنفيذي لا يمكنه تفاديها وعلى الأغلب أنها ستسبب بإغلاق البرنامج.
+
+ ولمعالجة أخطاء التنفيذ هذه وتحجيمها فبل حدوثها وفرت لنا لغات البرمجة وعلى رأسها الجافاسكريبت آلية تتمثل بوضع جمل استثنائية خاصة يتوقع من خلالها المبرمج أنواع أخطاء التنفيذ التي قد تحدث ويقوم ببرمجة حدث برمجي بكل استثناء ليتم تنفيذه بدلا من الخطا التنفيذي.

+ +

بصفة عامة، الاستثناءات هي عبارة عن آلية برمجية لمعالجة أخطاء التنفيذ المحتمل وقوعها.

+ +

 

+
+ +

يمكنك قذف (توليد)  الاستثناءات من خلال التعليمة throw والتعامل معها باستخدام التعليمة try...catch

+ + + +

انواع الاستثناءات

+ +

في جافا سكريبت، يمكن استخدام الكائنات لقذف/توليد الاستثناءات. ومع ذلك، ليس كل الكائنات القاذفة هي نفسها. من الشائع إلى حد ما، قذف الاعداد أو السلاسل الحرفية كاخطاء، الا انه في كثير من الأحيان سيكون أكثر فعالية استخدام أحد أنواع الاستثناءات التالية، والتي أنشئت خصيصا لهذا الغرض:

+ + + +

التعليمة throw

+ +

التعليمة throw تقذف الاخطاء. عند حدوث خطأ، عادة سوف تتوقف جافا سكريبت، وستولد رسالة للاعلان عن الخطأ. المصطلح التقني لهذه العملية هو : الجافاسكريبت ستقذف (throw) الخطأ. التعليمة throw تمكتك من انشاء خطأ حسب رغبتك. المصطلح التقني لهذه العملية هو: اقذف استثناءا (throw an exception).

+ +

إستخدِم التعليمة throw لقذف الإستثناء، عنما تريد قذف إستثناءا، عليك تحديد التعبير (expression) الذي سيحتوي على القيمة التي ستقذف:

+ +
throw expression;
+
+ +

يمكنك قذف اي استثناء، وليس مجرد تعبيرات من نوع معين. التعليمة البرمجية التالية تقذف استثناءات لمختلف انواع البيانات:

+ +
throw 'Error2';   // String type
+throw 42;         // Number type
+throw true;       // Boolean type
+throw {toString: function() { return "I'm an object!"; } };
+
+ +
ملحوظة : يمكنك تحديد كائن عندما ستقوم بقذف الاستثناء. يمكنك بعد ذالك الاشارة إلى خصائص الكائن في البلوك catch. يقوم المثال التالي بإنشاء الكائن myUserException من النوع UserException واستحدامه في التعليمة throw.
+ +
// 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');
+ +
+

لمزيد من المعلومات حول هذه التعليمة، راجع صفحة مرجع الجافا سكريبت  throw.

+
+ +

التعليمة try...catch

+ +

التعليمة try...catch تحدد بلوك من التعليمات البرمجية لتجربتها، و تنص على وجود واحد أو أكثر من الاستجابات التي ينبغي على الاستثناء ان يقذفها. إذا تم قذف الاستثناء، ستمسك به التعليمة  try...catch.

+ +

التعليمة try...catch تتكون من البلوك try الذي سيحتوي على واحدة أو أكثر من التعليمات البرمجية، والبلوك catch سيحتوي على التعليمات البرمجية التي تحدد ما يجب فعله اذا تم قذف الاستثناء من البلوك try. بمعنى اخر، في معظم الحالات. نريد من التعليمات البرمجية داخل البلوك try ان تسير بشكل طبيعي، وفي حالة حدوث مشاكل يمرّر التحكم الى البلوك catch. إذا كانت هناك احدى التعليمات البرمجية داخل البلوك try تقذف استثناءا، سيتم نقل التحكم فورا إلى البلوك catch. وإذا لم يتم إرسال أي استثناء من داخل البلوك try، فالبلوك catch لن يقم باي شئ. هذه التعليمة البرمجية يمكن ان تحتوي على البلوك finally والذي سينفذ بعد تنفيذ البلوك  try و catch، وايضا سينفذ قبل تنفيذ التعليمات البرمجية التي تلي التعليمة try...catch، اذا وجدت.

+ +


+ المثال التالى يستخدم التعليمة try...catch. ويقوم باستدعاء دالة تعود باسم الشهر من مصفوفة بناء على القيمة التي تم تمريرها إلى الدالة. إذا كانت القيمة لا تتوافق مع رقم الشهر (1-12)، سيولّد استثناء مع القيمة "InvalidMonthNo" فيما تقوم التعليمة البرمجية في البلوك catch بتعين القيمة unknown إلى المتغير monthName.

+ +
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

+ +

يمكنك استخدام البلوك  catch للامساك بجميع الاستثناءات التي سيتم قذفها من البلوك try.

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

البلوك catch يحدد الايدي catchID الذي سيمسك القيمة المحددة من طرف التعليمة throw، يمكنك استخدام هذا الايدي للحصول على معلومات حول الاستثناء الذي سيقذف. جافا سكريبت ستنشئ هذا الايدي عند دخوله الى البلوك catch. يبدا عمر هذا الايدي من لحظة دخوله الى البلوك catch، وينتهي عندما ينتهي البلوك catch من التنفيذ.

+ +

على سبيل المثال، التعليمة البرمجية التالية ستقذف استثناءا. عند حدوث الاستثناء، سيتم نقل التحكم الى البلوك catch.

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

The finally block

+ +

البلوك finally سيحتوي على التعليمات البرمجية التي سيقوم بتنفيذها بعدما تنفذ البلوكات try و catch، وايضا سينفذ قبل تنفيذ التعليمات البرمجية التي تلي التعليمة try...catch. سينفذ البلوك finally سواء تم قذف الاستثناء ام لا، اذا تم قذف الاستثناء، ستنفذ التعليمات البرمجية في البلوك finally حتى وان لم يتم معالجة الاستثناء في البلوك catch.

+ +

يمكنك استخدام البلوك finally لجعل السكريبت الخاص بك يفشل بأمان عند حدوث استثناء، على سبيل المثال، اذا كنت في حاجة إلى تحرير مورد، او لغلق ال flux، الخ. المثال التالي يفتح ملف ثم ينفذ التعليمات البرمجية لهذا ملف (server-side JavaScript يسمح لك بالوصول الى الملفات). اذا تم قذف استثناء في حين أن الملف مفتوح، البلوك finally ستغلق هذا الملف قبل فشل السكريبت.

+ +
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
+}
+
+ +

عندما سيقوم البلوك finally بارجاع قيمة، تصبح هذه القيمة قيمة الإرجاع من كامل المجموعة  try-catch-finally بغض النظر عن التعليمات البرمجية العائدة من البلوكات  try و catch.

+ +
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
+
+ +

الكتابة فوق القيم العائدة من قبل البلوك finally ينطبق أيضا على قذف الاستثناءات او اعادة القذف داخل البلوك catch:

+ +
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"
+ +

التعليمات try...catch المتداخلة

+ +

يمكن عمل واحدة او اكثر من التعليمات try...catch المتداخلة.  شرط عدم توفر try...catch الداخلية على البلوك catch، تتطلب وجود البلوك finally والتعليمة try...catch الخارجية سوف تستخدم البلوك catch ليتم التحقق من المطابقة. راجع nested try-blocks في صفحة المرجع الخاص بالتعليمة try...catch.

+ +

باستخدام الكائنات Error

+ +

اعتماداً على نوع الخطأ، من الممكن استخدام الخصائص name و message للحصول على رسالة أكثر دقة. عموما لدينا الخاصية name التي ستعرض نوع الخطا الذي حدث (مثلا: DOMException او Error). والخاصية message التي ستعرض رسالة الخطأ لوصف هذا الخطا (تستخدم عادة عندما نريد تحويل او عرض نص الخطأ). على سبيل المثال:

+ +
try {
+  throw new Error('Whoops!');
+} catch (e) {
+	if( e.message === 'Whoops!'){
+		e.message = "Costume message";
+	}
+  console.log(e.name + ': ' + e.message); // Error: Costume message
+}
+ +

اذا كنت ترغب في انشاء اخطاء خاصة بك، يمكتك استخدام المنشئ Error من أجل الاستفادة من خصائصه. على سبيل المثال:

+ +
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

+ +

ابتداءا من ECMAScript2015. اصبح لجافاسكريبت الكائن Promise والذي يسمح لك بالتحكم في التدفق والعمليات المتزامنة.

+ +

Promise هو احد هذه الحالات:

+ + + +

+ +

تحميل صورة ب XHR

+ +

مثال بسيط باستخدام Promise و XMLHttpRequest في مستودع الاكواد MDN GitHub. راجع المثال js-examples. يمكنك ايضا مراجعة see it in action. تم التعليق على كل خطوة لتمكينك من متابعة سير عملية Promise و XHR. هذا الإصدار من دون تعليقات، يعرض تدفق ال Promise:

+ +
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();
+  });
+}
+ +

للحصول على معلومات أكثر تفصيلاً، راجع {{jsxref("Promise")}} في صفحة المرجع.

+ +
+
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
+
+
diff --git a/files/ar/web/javascript/guide/grammar_and_types/index.html b/files/ar/web/javascript/guide/grammar_and_types/index.html new file mode 100644 index 0000000000..be90ff189a --- /dev/null +++ b/files/ar/web/javascript/guide/grammar_and_types/index.html @@ -0,0 +1,680 @@ +--- +title: قواعد اللغة وأنواع البيانات +slug: Web/JavaScript/Guide/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")}}
+ +

يناقش هذا الفصل. القواعد الأساسية لجافا سكريبت، والإعلان عن المتغيرات، وأنواع البيانات الحرفية.

+ +

الأساسيات

+ +
+

معظم التعبيرات الخاصة بجافا سكريبت مشتقة من Java، ولكنها تاثرت أيضا ب Awk، بيرل وبايثون.

+ +

الجافاسكريبت حساسة لحالة الاحرف myName ليس نفسه myname، الجافاسكريبت تستخدم مجموعة من رموز ال Unicode.

+ +

في الجافاسكريبت، التعليمات البرمجية تسمى {{Glossary("Statement", "statements")}}  وتكون مفصولة بفاصلة منقوطة (؛).  الفراغات، وعلامات التبويب (tabs) والأسطر الجديدة تسمى مساحة خالية.  يتم تحليل نص شيفرة المصدر لجافا سكريبت من اليسار إلى اليمين ويتم تحويلها إلى سلسلة من العناصر والمدخلات، وهي الرموز المميزة (tokens)، رموز التحكم (control characters)، ونهايات الاسطر (line terminators)، والتعليقات والمسافات الخالية، ECMAScript تحدد ايضا الكلمات المحجوزة مثل (if او var او return الخ)  والبيانات الحرفية، كما لها قواعد للإدراج التلقائي للفاصلة المنقوطة (ASI) لانهاء التعليمة البرمجية. ومع ذالك، من المستحسن دائماً إضافة الفاصلة المنقوطة (;) نهاية التعليمة البرمجية الخاصة بك لتجنب الاثار الجانبية، للحصول على مزيد من المعلومات، راجع قاموس جافا سكريبت.

+ +

التعليقات

+ +

صيغة التعليقات هي نفسها كما هو الحال في ++C و في العديد من اللغات الأخرى:

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

الاعلانات

+ +

هناك ثلاثة أنواع من الإعلانات في جافا سكريبت.

+ +
+
{{jsxref("Statements/var", "var")}}
+
الاعلان عن متغير (اي، الكلمة المحجوزة var متبوعة باسم المتغير var x)، تهيئته (اي، اسناد قيمة اولية له var x = value ) / اختياري.
+
{{jsxref("Statements/let", "let")}}
+
الاعلان عن متغير محلي ضمن نطاق الكتلة (ال block هو مجموعة من التعليمات البرمجية بين اقواس متعرجة {})، تهيئته / اختياري.
+
{{jsxref("Statements/const", "const")}}
+
الاعلان عن ثابت قابل للقراءة فقط.
+
+ +

المتغيرات

+ +

يمكنك استخدام المتغيرات كأسماء رمزية للقيم في التطبيق الخاص بك. أسماء المتغيرات، تسمى {{Glossary("Identifier", "identifiers")}}, وتخضع لقواعد معينة.

+ +

المتغير في جافاسكريبت، يجب أن يبدأ بحرف، أو رمز (_)، أو علامة الدولار ($). يمكن أيضا أن تكون الأحرف اللاحقة أرقاما (0-9). ولأن الجافاسكريبت حساسة لحالة الأحرف، فإن الحروف تشمل الأحرف من "A" الى "Z" (أحرف كبيرة) او أحرف من  "a" الى "z" (أحرف صغيرة).

+ +

يمكنك استخدام معظم أحرف ال ISO 8859-1 أو Unicode مثل å و ü في المتغيرات. لمزيد من المعلومات راجع مذه المدونة كما يمكنك أيضا استخدام  Unicode escape sequences كرموز مع المتغيرات.

+ +

بعض الامثلة عن اسماء المتغيرات الجائزة :  Number_hits, temp99, $credit, and_name.

+ +

الاعلان عن المتغيرات

+ +

يمكنك تعريف متغير بثلاث طرق:

+ + + +

اختبار المتغيرات

+ +

الاعلان عن متغير باستخدام var او let من دون تهيئته، سيتم تهيئته بالقيمة {{jsxref("undefined")}} (بشكل تلقائي من قبل الجافاسكريبت).

+ +
+

ملاحظة: جافا سكريبت في الوضع الصارم ("use strict") لا تسمح باستخدام المتغيرات إذا لم يتم الإعلان عنها

+
+ +

محاولة الوصول إلى متغير غير معلن عنه سيؤدي الى ال {{jsxref("ReferenceError")}}. وايضا محاولة الوصول الى متغير لم يتم تهيئته بعد سيعود ب undefined :

+ +
var a;
+console.log("The value of a is " + a); // logs "The value of a is undefined"
+console.log("The value of b is " + b); // throws ReferenceError exception
+
+ +

يمكنك استخدام undefined لاختبار ما إذا كان المتغير مهيأ ام لا. في التعليمة البرمجية التالية، المتغير input غير مهيأ، ستقوم التعليمة if باختبار ما اذا كان فعلا المتغير input غير مهيأ، بمعنى اخر (هل صحيح/true ان المتغير input غير مهيأ).

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

القيمة undefined تتصرف ك false عندما تستخدم في السياق المنطقي. على سبيل المثال، التعليمة البرمجية التالية ستقوم بتنفيذ الدالة myFunction بسبب ان العنصر الاول في المصفوفة myArray غير مهيأ:

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

تذكير:  تذكر ان "المتغير الغير مهيأ يتم تهيئته بشكل تلقائي بالقيمة undefined" كما ذكرنا اعلاه.

+
+ +

القيمة undefined تتحول الى NaN (ليسا رقما) عندما تستخدم في السياق الرقمي.

+ +
var a;
+a + 2 = NaN
+ +

عند اختبار متغير يحمل القيمة {{jsxref("null")}} ستتصرف القيمة null ك 0 في السياق الرقمي وك false في السياق المنطقي على سبيل المثال:

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

نطاق المتغيرات - Variable scope

+ +

عندما سنقوم بتعريف متغير خارج أي دالة/وظيفة سيسمى متغير عام، لأنه سيصبح متاحا لأية تعليمات برمجية أخرى في المستند الحالي. وعندما سنقوم بتعريف متغير داخل دالة/وظيفة، سيسمى متغير محلي، لأنه سيصبح متاحا فقط داخل هذه الدالة.

+ +

في جافاسكريبت قبل ECMAScript 2015، لم يكن للتعليمة البرمجية block statement نطاق (scope) خاص بها، المتغير الذي يتم تعريفه داخل block هو اما متغير محلى للدالة او متغير محلي للنطاق العام حسب تواجد هذا البلوك.

+ +

يبين المثال التالى كيف ان ال block ليس له نطاق خاص به، مخرجات التعليمة البرمجية التالية ستكون 5، بسبب ان المتغير x تم تعريفه في النطاق العام وليس في نطاق ال block، وفي هذه الحالة ال block هي التعليمة if.

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

يتغير هذا السلوك، عند الاعلان عن متغير باستخدام let المعتمدة في ECMAScript 6، الان اصبح لل block نطاقا خاصا به: 

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

رفع المتغيرات - Variable hoisting

+ +

الرفع هو السلوك الافتراضي لجافا سكريبت، تقوم جافاسكريبت برفع جميع المتغيرات او الدوال او اي شئ تم الاعلان عنه، إلى أعلى النطاق الحالي (في الجزء العلوي من التعليمة البرمجية الحالية أو الوظيفة الحالية بشكل اوتوماتيكي). في جافاسكريبت، يمكن الاعلان عن متغير بعد استخدامه. او بعبارة اخرى يمكن استخدام المتغير قبل الاعلان عنه.

+ +

لو تاملت قليلا في التعليمة البرمجة التالية، ستتسائل ما الذي جعل المتغير x يعود ب undefined وليس ب ReferenceError. السبب هو ان الجافاسكريبت ترفع الاعلان (var x) فقط، ولا ترفع التهيئة (3=). وبالتالي وبسبب الرفع الذي حدث "في الخفاء"، x اعلن عنه قبل استخدامه، لكن بسبب ان التهيئة لم ترفع، فقيمة x ستعود ب undefined. ونفس الشئ حصل مع المتغير myvar، بحيث تم رفعه الى اعلى نطاق الدالة. فيما تم رفع المتغير x الى اعلى النطاق العام.

+ +
/*---Example 1---*/
+
+console.log(x === undefined); // logs "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";
+})();
+
+ +

الامثلة اعلاه، ستفسر بالشكل التالي:

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

لتجنب الكثير من الاخطاء، حاول دائما الاعلان عن المتغيرات اعلى اي نطاق. بما ان هذا هو السلوك الذي تعتمده جافاسكريبت لتفسير التعليمة البرمجية خاصتك (بخصوص هذه الجزئية)، فالسلوك المتوقع منك ايضا كمبرمج متمرس هو مجاراة الجافاسكريبت. وايضا هذا يجعل من التعليمات البرمجية خاصتك اكثر وضوحا واكثر قابلية للقراءة.

+ +

في ECMAScript 2015، المتغير let سوف لن يتم رفعه الى اعلى نطاق ال block. واستخدام متغير داخل block قبل الاعلان عنه سينتج عنه ReferenceError. لان المتغير يعتبر في "منطقة زمنية ميتة" من بداية ال block حتى يتم معالجته بالإعلان.

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

رفع  الدوال - Function hoisting

+ +

بالنسبة للدوال، فقط ال function declaration هي التي سترفع الى الاعلى وليست ال 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');
+};
+
+ +

المتغيرات العامة

+ +

المتغيرات العامة، في حقيقة الامر هي خصائص للكائن العام. في صفحات الويب الكائن العام هو window. لذا يمكنك انشاء او الوصول إلى المتغيرات العامة باستخدام الصيغة window.variable.

+ +

كما يمكنك ايضا الوصول إلى المتغيرات العامة المعلن عنها في نافذة أو frame من نافذة اخرى او frame عن طريق تحديد النافذة او اسم ال frame. على سبيل المثال، اذا كان لدينا متغير معلن عنه في الوثيقة، واسمه phoneNumber,  يمكنك الوصول الى هذا المتغير من ال iframe باستخدام الصيغة parent.phoneNumber

+ +

الثوابت - Constants

+ +

يمكنك إنشاء ثابت للقراءة فقط، والمسمى بالكلمة المحجوزة {{jsxref("Statements/const", "const")}} طريقة التعبير عن الثابت هي نفسها طريقة التعبير عن المتغير: يجب ان يبدا بحرف او underscore او ($)dollar sign  ويمكن يحتوي على alphabetic، ارقام، او underscore او رموز. 

+ +
const prefix = '212';
+
+ +

الثابت، لا يمكن تغيير قيمته من خلال الاحالة او باعادة الاعلان عنه اثناء تشغيل السكريبت. ولا بد من تهيئته.

+ +

قواعد نطاق الثابت هي نفسها قواعد المتغير let فيما يخص نطاق ال block. اذا لم يتم تعيين الكلمة المحجوزة const سيتم معاملته معاملة المتغير.

+ +

اسم الثابت لا يجب ان يكون هو نفسه اسم دالة او متغير في نفس النطاق. على سبيل المثال:

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

ومع ذلك، خصائص الكائنات التي يتم تعيينها إلى الثوابت غير محمية، حيث سيتم تنفيذ التعليمة التالية دون مشاكل.

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

هياكل البيانات والأنواع - Data structures and types

+ +

أنواع البيانات

+ +

المعيار الاحدث ل ECMAScript يحدد سبعة من انواع البيانات:

+ + + +

على الرغم من أن هذه الكمية من أنواع البيانات صغيرة نسبيا، الا أنها تتيح لك القيام بمهام مفيدة مع التطبيقات الخاصة بك. الكائنات {{jsxref("Object", "Objects")}} والدوال {{jsxref("Function", "functions")}} هي العناصر الأساسية الأخرى في اللغة، يمكنك اعتبار الكائنات كحاويات لمجموعة من المتغرات المرتبطة بالكائن، والدوال هي الوظائف التي سيقوم التطبيق الخاص بك بتنفيذها.

+ +

تحويل نوع البيانات - Data type conversion

+ +

الجافاسكريبت لغة حيوية، وهذا يعني انك لست بحاجة لتحديد نوع البيانات للمتغير اثناء تعريفه، على غرار لغات برمجة اخرى (جافا مثلا)، لانه سيتم تحويل أنواع البيانات تلقائياً حسب الحاجة أثناء تنفيذ السكريبت. على سبيل المثال، يمكنك تعريف متغير كالتالي:

+ +
var answer = 42;
+
+ +

وفي وقت لاحق، يمكنك تغيير نوع البيانات، من النوع Number الى النوع String، عن طريق تعيين سلسلة حرفية لنفس المتغير، على سبيل المثال:

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

بفضل حيوية الجافا سكريبت، فهذه التعليمة البرمجية لن تتسبب في اية رسالة خطأ.

+ +

اثناء الجمع بين القيم الرقمية والسلاسل الحرفية باستخدام عامل التشغيل (+)، فجافاسكريب تحول القيم الرقمية الى سلاسل حرفية. على سبيل المثال، انظر في التعليمات البرمجية التالية:

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

في التعبيرات التي تحتوي على عوامل أخرى، جافا سكريبت لا تقوم بتحويل القيم الرقمية إلى سلاسل حرفية. على سبيل المثال:

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

تحويل القيم النصية إلى أرقام

+ +

في حالة أن لدينا قيمة تمثل عدد في الذاكرة وهي على شكل سلسلة حرفية ("10")، ونريد تحويلها الى قيمة رقمية، سنحتاج الى وظائف جاهزة في الجافاسكريبت تقوم بعملية التحويل.

+ + + +

المثال التالي يبين كيفية استخدام الوظيفة parseInt ببارامتر واحد، لمزيد من المعلومات حول البرامتر الثاني واشياء اخرى، راجع {{jsxref("parseInt", "()parseInt")}}:

+ +
var str = "10";
+console.log( typeof str ) // string
+var parse = parseInt(str)
+console.log( typeof parse ) // number.
+ +

المثال التالي يبين كيفية استخدام الوظيفة parseFloat، لمزيد من المعلومات، راجع {{jsxref("parseFloat", "()parseFloat")}}

+ +
var str = "3.14";
+console.log( typeof str ) // string
+var parse = parseInt(str)
+console.log( typeof parse ) // number.
+ +

طريقة بديلة لتحويل قيمة رقمية على شكل سلسلة حرفية، باستخدام العامل (unary plus)+

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

البيانات الحرفية - Literals

+ +

المقصود بالبيانات الحرفية، هو استخددام الكائن بالصيغة الاسهل، مثلا، بدلا من استخدام الكائن new Array(elm1,elm2...) نستخدم [...elm1,elm2] وهكذا مع جميع الكائنات الاخرى.

+ +

يمكنك استخدام البيانات الحرفية لتمثيل القيم في جافا سكريبت. وهي قيم ثابتة، ليست متغيرات، والتي ترد حرفيا في السكريبت. يصف هذا القسم الأنواع التالية من البيانات الحرفية :

+ + + +

بيانات المصفوفة الحرفية - Array literals

+ +

بيانات المصفوفة الحرفية، هي قائمة تتكون من صفر او اكثر من التعبيرات، كل تعبير فيها يمثل عنصر المصفوفة، محاطة بأقواس مربعة ([]). عندما تقوم بإنشاء مصفوفة باستخدام البيانات الحرفية ، ستقوم بتهيئتها بقيم محددة لتكوين عناصرها، طول المصفوفة هو عدد البارامترات/العناصر المحددة لها.

+ +

ينشئ المثال التالي مصفوفة القهوة مع ثلاثة عناصر وطولها ثلاثة:

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

ملاحظة: بيانات المصفوفة الحرفية هي نوع من مهيئ الكائن.  Using Object Initializers.

+
+ +

إذا تم إنشاء مصفوفة باستخدام البيانات الحرفية في سكريبت على أعلى مستوى (top-level script)، فجافاسكريبت ستفسر هذه المصفوفة في كل مرة يتم اختبار التعبير الذي يحتوي على المصفوفة. بالإضافة الى ذالك، البيانات الحرفية المستخدمة في دالة يتم إنشاءها كل مرة يتم فيها استدعاء الدالة. 

+ +

 البيانات الحرفية هي كذالك Array objects راجع {{jsxref("Array")}} و Indexed collections لمعرفة تفاصيل ال Array objects.

+ +

فواصل إضافية في ال array literals

+ +

لست بحاجة لتحديد جميع العناصر في بيانات المصفوفة الحرفية. اذا قمت بوضع فاصلتات متتاليتان سيم انشاء المصفوفة مع undefined مكان العنصر الغير محدد.

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

تحتوي هذه المصفوفة على عنصرين بقيم، وعنصر واحد فارغ (fish[0] هو "Lion"، و fish[1] هو undefined، و fish[2] هو "Angel").

+ +

إذا قمت بتضمين فاصلة زائدة في نهاية قائمة العناصر، سيتم تجاهل تلك الفاصلة. في المثال التالي، طول المصفوفة هو ثلاثة. وليس هناك myList[3]. جميع الفواصل الأخرى في القائمة تشير الى عنصر جديد.

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

في المثال التالي، طول المصفوفة هو أربعة، و myList[0] و myList[2] في عداد المفقودين.

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

في المثال التالي، طول المصفوفة أربعة، myList[1] و myList[3] في عداد المفقودين. وسيتم تجاهل الفاصلة الأخيرة فقط.

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

فهم سلوك الفواصل الاضافية مهم لفهم جافا سكريبت كلغة، ولكن عند كتابة التعليمات البرمجية الخاصة بك: من الافضل الإعلان الصريح عن العناصر المفقودة ب undefined، مثل هذه الممارسات ستزيد من وضوح التعليمات البرمجية الخاصة بك ويصبح من السهل صيانتها.

+ +
+

ملاحظة: يمكن للفواصل الزائدة ان تخلق أخطاءا في الاصدارات القديمة من المتصفحات. من الافضل إزالتها.

+
+ +

Boolean literals

+ +

النوع Boolean يتكون من بيانين حرفيين وهما :  true و false.

+ +

لا ينبغي الخلط بين القيم المنطقية الاولية true و false مع القيم true و false لل Boolean object. الكائن Boolean هو من يحتضن انوع البيانات المنطقية الاولية. راجع {{jsxref("Boolean")}} لمزيد من المعلومات.

+ +

الأعداد الصحيحة - Integers

+ +

يمكن التعبير عن الأعداد الصحيحة بالنسبة لكل من العدد الصحيح العشري ب (base 10)، ونظام العد السداسي عشر ب (base 16) والرقم الثماني ب (base 8) والثنائي ب (base 2)  .

+ + + +

بعض الأمثلة عن البيانات الحرفية لعدد صحيح :

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

لمزيد من المعلومات، راجع Numeric literals in the Lexical grammar reference.

+ +

بيانات العدد الكسري الحرفي

+ +

البيانات الحرفية لعدد كسري  يمكن أن تتكون من الأجزاء التالية:

+ + + +

الأس هو "e" أو "E" متبوعاً بعدد صحيح، والذي يمكن توقيعه (يسبقه "+" أو "-"). يجب أن يكون قيمة حرفية floating-point ويجب ان يحتوي على رقم واحد على الأقل والنقطة العشرية أو "e"  (أو "E").

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

على سبيل المثال:

+ +
3.14
+2345.789
+.3333333333333333333
+-.283185307179586
+
+ +

بيانات الكائن الحرفي - Object literals

+ +

بيانات الكائن الحرفية هي عبارة عن قائمة تتكون من صفر او اكثر من الازواج، كل زوجين  عبارة عن اسم خاصية الكائن وقيمتها، محاطة بأقواس متعرجة ({}). لا يجب استخدام البيانات الحرفية للكائن في بداية التعليمة البرمجية خاصتك. لان هذا سيؤدي إلى خطأ او سيقوم بسلوك عكس المتوقع منه، بسبب ان الجافاسكريبت ستفسر } على انه بداية ل block.

+ +

في المثال التالي. العنصر الاول للكائن car يمثل الخاصية  myCar، تحمل القيمة النصية "Saturn"، العنصر الثاني هي الخاصية getCar، قيمتها هو ناتج الدالة carTypes("Honda")، العنصر الثالث، هي الخاصية special، قيمتها متغير خارجي وهو  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
+
+ +

بالإضافة إلى ذلك، يمكنك استخدام قيمة رقمية أو سلسلة حرفية كاسم للخاصية، كما يمكنك ايضا انشاء كائن داخل كائن آخر. يبين المثال التالي كيفية انشاء هذه الخيارات.

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

أسماء خصائص الكائن يمكن أن تكون أي سلسلة حرفية، بما في ذالك السلسلة الحرفية الفارغة, اذا كان اسم الخاصية عبارة عن احد المعرفات identifier، الغير مسموح بها (ما لا يمكن استخدامه كاسم للمتغر مثلا) او ان يكون اسم الخاصية عبارة عن رقم، فيجب إحاطتها بعلامات الاقتباس. اسماء الخاصية الغير مسموح بها كمعرفات لا يمكن الوصول اليها بطريقة نقطة التدوين (.)، وانما تستخدم طريقة الاقواس المربعة ("[]") للوصول اليها او التعديل عليها.

+ +
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!
+ +

ابتداءا من ES2015، اصبح من الممكن : تعيين ال prototype  أثناء إنشاء الكائن. استخدام التعيين المختصر ك  foo: foo، تعيين الوظائف، استدعاء وظائف الكائن الاب بواسطة super، استخدام أسماء الخصائص المحوسبة مع التعبيرات.

+ +
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
+};
+ +

يبين المثال التالي الطرق الصحيحة لكيفية الوصول الى الكائن:

+ +
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

+ +

Regex هو نمط (pattern) محصور بين خطوط مائلة. يبين المثال التالي كيفبة التعبير عن بيانات التعبيرات القياسية الحرفية.

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

بيانات السلاسل النصية الحرفية - String literals

+ +

السلسلة النصية، هي عبارة عن صفر أو أكثر من الأحرف محاطة بعلامات اقتباس اما منفردة (') أو مزدوجة ("). يبين المثال التالي كيفية استخدام كل من الاقتباسات المنفردة والمزدوجة:

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

من الممكن استدعاء وظائف الكائن String على السلاسل الحرفية. تقوم الجافاسكريبت بتحويل السلاسل الحرفية الى الكائن String بشكل مؤقت، بعدما تستدعى الوظائف، يتم استبعاد/تدمير الكائن String المؤقت، يمكنك ايضا استخدام  الخاصية String.length مع القيم النصية:

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

ابتداءا من ES2015، يمكنك استخدام البيانات الحرفية كقوالب  (template literals)، هذه القوالب النصية هي نفسها المستخدمة في  Perl ،Python، الخ. يمكنك استخدامها لانشاء سلسلة حرفية واحدة على عدة اسطر دون الحاجة لاستخدام اسلوب التهريب (اضافة "\" في نهاية كل سطر). يمكن من خلالها ايضا إنشاء سلاسل حرفية جديدة اعتمادا على مجموعة متقطعة من السلاسل الحرفية المحددة سلفا وذالك من خلال هذه الصيغة الجديدة { result }$، القيمة الممرة result هي القيمة التي ستظهر مع السلسلة الحرفية الجديدة،  وهي عبارة عن مخرجات لاي تعليمة برمجية اخرى مثل (function, literal object, var...).  وايضا يمكنك من خلالها تجنب هجمات الحقن (injection attacks). 

+ +
// 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);
+ +

من الأفضل استخدام السلاسل الحرفية قدر الامكان، الا اذا كنت في حاجة ماسة لاستخدام الكائن String، وقتها يمكنك استخدامه ايضا. راجع الكائن {{jsxref("String")}} للاطلاع على كافة التفاصيل.

+ +

استخدام الرموز الخاصة مع السلاسل النصية

+ +

بالإضافة إلى الرموز العادية، يمكنك أيضا إدراج الرموز الخاصة مع السلاسل الحرفية، كما هو موضح في المثال التالي.

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

يبين الجدول التالي، الرموز الخاصة التي يمكنك استخدامها مع السلاسل الحرفية لجافاسكريبت.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
جدول الرموز الخاصة لجافاسكريبت
CharacterMeaning
0\Null Byte  - بايت فارغ
b\Backspace  - مسافة للخلف
f\Form feed  -  نموذج تغذية
n\New line  -  سطر جديد
r\Carriage return  -  حرف الإرجاع
t\Tab  -  علامة التبويب
v\Vertical tab - علامة التبويب العمودي
'\single quote  -  علامة اقتباس مفردة
"\Double quote  -  علامة اقتباس مزدوجة
\\Backslash character  -  حرف الخط المائل العكسي
XXX\  الحرف مع Latin-1 لتحديد ترميز من خلال الرجوع الى الوراء بثلاثة ارقام ثمانية XXX ما بين 0 و 377. على سبيل المثال, 251\ هو تسلسل ثماني لرمز حقوق النشر.  
xXX\الحرف مع Latin-1 لتحديد ترميز  من خلال ارقام نظام العد السداسي عشر  XX بين 00 و FF. على سبيل المثال , xA9\ هو تسلسل نظام العد السداسي عشر لرمز حقوق النشر.
uXXXX\الحرف Unicode محدد من خلال اربعة ارقام من نظام العد السداسي عشر  XXXX. على سبيل المثال , u00A9\ هو تسلسل Unicode لرمز حقوق النشر. راجع {{anch("Unicode escape sequences")}}.
u{XXXXX}\كود ال Unicode لتهريب النقطة، على سبيل المثال، u{2F804}\ هي تماما مثل  تهريب اليونيكود نفسه  uD87E\uDC04\
+ +

تهريب الرموز - Escaping characters

+ +

الرموز الخاصة التي لم ترد في الجدول اعلاه، تم تجاهلها، لانها اصبحت  مستنكرة وينبغي تجنبها.

+ +

يمكنك إدراج علامة اقتباس داخل سلسلة حرفية شرط ان يسبقها الرمز backslash. وتعرف هذه العملية بتهريب علامة الاقتباس. على سبيل المثال:

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

ونتيجة لذالك سنحصل على السلسلة الحرفية التالية:

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

لتضمين الرمز  backslash نفسه  في سلسلة حرفية، يجب  عليك تهريبه ايضا ب backslash ثانية. وبالتالي سيتحول الى رمز عادي، قابل للقراءة. على سبيل المثال، لتعيين مسار الملف c:\temp الى سلسلة حرفية، استخدم التالي:

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

يمكنك ايضا تهريب فواصل الأسطر (line breaks)، وذالك من خلال اضافة backslash في نهاية كل جزء من اجزاء السلسلة الحرفية. الغرض هذه العملية هو الحد من طول التعليمة البرمجية فقط، ولهذا فالسلسلة الحرفية الجديدة، لن تتضمن اي من هذه السلاشات، وكذالك لن تتضمن اية فواصل الأسطر (<line break = <br) المخفية.

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

على الرغم من ان جافاسكريبت لا تتوفر عل التعبير "heredoc" المستخدم في كثير من لغات البرمجة الاخرى (php مثلا) والذي يمكتك من التعامل مع السلاسل الحرفية بطريقة مميزة. الا انه من من الممكن تحقيق ما يشبهها من خلال التعبير التالي:

+ +
var poem =
+"Roses are red,\n\
+Violets are blue.\n\
+I'm schizophrenic,\n\
+And so am I."
+
+ +

للمزيد من المعلومات

+ +

تم التركيز في هذا الفصل على اساسيات صياغة الاعلانات والانواع. لدراسة المزيد حول JavaScript language constructs. راجع أيضا الفصول التالية في هذا الدليل:

+ + + +

في الفصل التالي ان شاء الله، سنلقي نظرة على كيفية السيطرة على تدفق البيانات ( control flow constructs ) ومعالجه الأخطاء.

+
+ +

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

diff --git a/files/ar/web/javascript/guide/index.html b/files/ar/web/javascript/guide/index.html new file mode 100644 index 0000000000..8a2410f634 --- /dev/null +++ b/files/ar/web/javascript/guide/index.html @@ -0,0 +1,116 @@ +--- +title: دليل جافا سكريبت +slug: Web/JavaScript/Guide +tags: + - جافا سكربيت + - دليل +translation_of: Web/JavaScript/Guide +--- +
{{jsSidebar("JavaScript Guide")}}
+ +

دليل جافا سكريبت يظهر لك كيفية استخدام جافا سكريبت ويعطيك لمحة عامة عن اللغة. إذا كنت تريد أن تبدأ مع جافا سكريبت أو البرمجة بشكل عام، راجع المقالات في منطقة التعليم. إذا أردت الحصول على معلومات شاملة حول ميزة اللغة، ألقي نظرة على مرجع جافا سكريبت.

+ +

الفصول

+ +

هذا الدليل مقسم إلى عدة فصول:

+ + + + + +

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

diff --git a/files/ar/web/javascript/guide/introduction/index.html b/files/ar/web/javascript/guide/introduction/index.html new file mode 100644 index 0000000000..681bb0276a --- /dev/null +++ b/files/ar/web/javascript/guide/introduction/index.html @@ -0,0 +1,159 @@ +--- +title: تقديم +slug: Web/JavaScript/Guide/Introduction +tags: + - جافا سكربيت + - مرشد +translation_of: Web/JavaScript/Guide/Introduction +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
+ +

يقوم هذا الفصل بتقديم جافا سكريبت ويناقش بعض مفاهيمها الأساسية.

+ +

ما يجب أن تعرفه مسبقا

+ +
+

يفترض أن تكون لديك خلفية حول المكونات التالية:

+ + + +

أين تجد المعلومات عن الجافا سكربيت

+ +

وثائق جافا سكربيت على MDN تشتمل على مايلي:

+ + + +

إذا كنت جديدا على جافا سكريبت، أبدء مع المقالات في منطقة التعلم و دليل جافا سكريبت. حتى تصبح ملما بالأساسيات، ومن ثم يمكنك استخدام مرجع جافا سكربيت للحصول على مزيد من التفاصيل حول الكائنات الفردية والبيانات.

+ +

ما هي جافاسكريبت؟

+ +

الجافاسكريبت هي لغة برمجة كائنية التوجة ومتعددة المنصات. هي لغة صغيرة وخفيفة الوزن. داخل بيئة المضيف (على سبيل المثال، متصفح ويب)، في هذه البيئة يمكنك استخدامها على الكائنات.

+ +

تحتوي جافاسكريبت على مكتبة قياسية من الكائنات، مثل Array، Date، وMath، ومجموعة أساسية من العناصر اللغوية مثل العوامل، بنى التحكم، والتصريحات. جوهر جافا سكريبت هو قابليتها للتعامل مع مجموعة متنوعة من الكائنات التي تكون مكملة مع كائنات إضافية. على سبيل المثال:

+ + + +

جافا سكريبت وجافا

+ +

جافا سكريبت وجافا متشابهتان في بعض النواحي، ولكنها تختلف اختلافا جوهريا عن بعضها البعض في نواح اخرى. لغة جافا سكريبت تبدو وكأنها جافا، لكن لا يتم كتابتها بشكل ثابت، وطباعة جافا سكريبت ضعيفة (في حين أنها قوية في جافا). بناء الجملة في تعبيرات جافا سكريبت متشابهة جدا لجافا، في اصطلاحات التسمية والبنى الشرطية على سبيل المثال، وهذا احد الأسباب التي ادت الى إعادة تسمية لغة LiveScript إلى JavaScript.

+ +

على عكس جافا التي لها نظام المترجم الزمني  compile-time system للاعلان عن الكلاسات، فجافا سكريبت تدعم نظام وقت التشغيل  runtime system ولها بعض أنواع البيانات لتمثيل الأرقام، القيم المنطقية، والسلاسل النصية (و أمور أخرى). تعتمد جافاسكريبت على النموذج الأولي  prototype-based object model لعمل رابط بين الكائنات بينما تستخدم جافا نموذجا أكثر شيوعا يستند إلى الكلاسات class-based object model.  النماذج-البروتوتايبس تسمح بخلق ديناميكية عالية فيما يخص الوراثة. وبالتالي، فإن الخصائص التي يرثها كائن ما، قد تختلف مع مرور الوقت. كما تدعم جافاسكريبت الوظائف دون متطلبات إعلانية خاصة. الوظائف يمكن أن تكون خصائص لكائن،

+ +

جافا سكريبت هي لغة "حرة" مقارنة بجافا. لذا فليس من الضروري، الاعلان عن نوع المتغيرات او الدوال او حتى الكلاسات. وليس من الضروري معرفة ما إذا كانت الدالة/الوظيفة عامة أو خاصة أو محمية، ولا توجد واجهات لتنفيذها. ولا يتم كتابة نوع المتغيرات والبارامترز والوظائف بشكل صريح.

+ +

جافا هي لغة برمجة، تستخدم الكلاسات، مصممة للتشغيل بسرعة وضمان أمن الكتابة. وهذا يعني، على سبيل المثال، أنه لا يمكن تحويل عدد صحيح إلى كائن أو أنه لا يمكنك الوصول إلى الذاكرة الخاصة عن طريق تحريف  Java bytecodes. نموذج الكلاسات المستخدم من قبل جافا، يعني أن البرنامج يتكون فقط من الكلاسات والوظائف. هذا النوع من الميراث القائم على الكلاسات، مرتبط بالكتابة القوية، ينتج هياكل مقترنة بقوة وتسلسلات هرمية للكائن. لهذه الأسباب، يمكن أن تظهر جافا كلغة أكثر تعقيدا من جافا سكريبت.

+ +

على عكس جافا، فجافاسكريبت سليلة من لغات اخرى أخف وزنا، وديناميكية مثل HyperTalk و dBASE. وتستهدف لغات البرمجة النصية هذه، جمهورا أكبر مع بنية أبسط، وخصائص محلية متخصصة، والحد الأدنى من المتطلبات المسبقة لإنشاء الكائنات.

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

جافا سكريبت مقارنة مع جافا

+
جافا سكربيتجافا
تعتمد على رابط البروتوتايب. لا يوجد تمييز بين أنواع الكائنات. تتم الوراثة من خلال آلية البروتوتايب، ويمكن إضافة الخصائص والوظائف إلى أي كائن حيويتعتمد على الكلاسات (Class-based). وتنقسم الكائنات إلى فئات وحالات، يتم الإرث من خلال التسلسل الهرمي للكلاسات. لا يمكن إضافة الكلاسات والحالات ديناميكيا إلى الخصائص والوظائف.
لا يتم الاعلان عن نوع البيانات المتغيرة (الكتابة ديناميكية).يجب تعريف أنواع البيانات المتغيرة (الكتابة ثابتة).
لا يمكن الكتابة تلقائيا إلى القرص الثابت. +
+
+
+
 
+ +
يمكن الكتابة تلقائيا إلى القرص الثابت.
+
+
+
+ +
+
 
+
+
+ +

لمزيد من المعلومات حول الاختلافات بين جافا سكريبت وجافا، انظر الفصل تفاصيل عن الكائن.

+ +

جافا سكريبت والمواصفات ECMAScript

+ +

 جافا سكريبت موحدة عن طريق Ecma International - الجمعية الأوروبية لتوحيد النظم المعلوماتية والاتصالات (ECMA اختصارا لجمعية مصنعي الكمبيوتر الأوروبية تاريخيا) والتي تنص على لغة برمجة موحدة، هذا الإصدار القياسي من جافا سكريبت، يسمى  ECMAScript. هذا الاصدار، يتصرف بشكل متطابق في جميع التطبيقات المتوافقة مع المعايير. يمكن للشركات استخدام هذه اللغة القياسية لتطوير طريقة تنفيذ جافا سكريبت. يتم توثيق ECMAScript القياسية مع ECMA-262. انظر رؤية جديد جافا سكريبت لمعرفة المزيد عن الاصدارات المختلفة من جافا سكريبت وطبعات مختلفة من مواصفات ECMAScript.

+ +

كما إعتُمِدت ECMA-262 من قبل ISO  المنظمة الدولية للتوحيد القياسي ك ISO-16262.  كما يمكنك أيضا العثور على المواصفات على موقع Ecma International. مواصفات ECMAScript  لا تصف نموذج الكائن المستند  (DOM)، الذي يتم توحيده من قبل اتحاد شبكة الويب العالمية (W3C). وDOM يحدد الطريقة التي تعرض بها كائنات المستند HTML في السكريبت الخاص بك. للحصول على فكرة أفضل حول التقنيات المختلفة التي يتم استخدامها عند البرمجة مع جافا سكريبت، راجع مقالة جافا سكريبت نظرة عامة التكنولوجيات.

+ +

وثائق جافا سكريبت مقابل المواصفات ECMAScript

+ +
+
مواصفات ECMAScript هي مجموعة من المتطلبات لتنفيذ ECMAScript. من المفيد إذا كنت ترغب في تنفيذ ميزات اللغة المتوافقة مع المعايير القياسية في تنفيذ ECMAScript  أو في احدى المحركات SpiderMonkey في فايرفوكس، أو V8 في كروم).
+ +
 
+
+ +

ليس المقصود من مواصفات ال ECMAScript هو دعم برمجة السكريبت. توفر وثائق جافا سكريبت معلومات لكتابة النصوص البرمجية.

+ +

يستخدم مواصفات ECMAScript أحيانا مصطلحات وصياغات قد تبدو غريبة لمطور جافا سكريبت. على الرغم من أن وصف اللغة يختلف بين ECMAScript، وبين وثائق جافا سكريبت، اللغة نفسها لا تزال هي نفسها. تدعم جافاسكريبت جميع الميزات المميزة في مواصفات ECMAScript.

+ +

تصف وثائق جافا سكريبت جوانب اللغة التي يمكن استخدامها من قبل مطوري جافا سكريبت.

+ +

الشروع في العمل مع جافا سكريبت

+ +

الشروع في العمل مع جافا سكريبت سهل: كل ما تحتاجه هو متصفح ويب حديث. يتضمن هذا الدليل بعض ميزات جافا سكريبت المتوفرة فقط في أحدث إصدارات فايرفوكس، لذا يوصى باستخدام احدث إصدار من فايرفوكس لتجربة الأمثلة المقدمة.

+ +

هناك أداتان هما جزءا من فايرفوكس، وهي مفيدة لتجربة واختبار شفرة جافا سكريبت، هما: وحدة تحكم الويب Console وقائمة جافاسكريبت Scratchpad .

+ +

وحدة تحكم ويب

+ +

وحدة تحكم ويب يعرض لك معلومات عن صفحة الويب التي تم تحميلها حاليا، ويشمل أيضا سطر الأوامر الذي يمكنك استخدامه لتنفيذ اكواد الجافا سكربت في الصفحة الحالية.

+ +

لفتح وحدة تحكم الويب (Ctrl+Shift+K) او F12،  في وحدة التحكم، هناك سطر الأوامر الذي يمكنك استخدامه لادخال اكواد جافا سكريبت، ويظهر الناتج في الجزء أعلاه:

+ +

+ +

المسودة

+ +

تعتبر وحدة تحكم الويب كبيرة بالنسبة لتنفيذ سطر واحدة من جافا سكريبت، ولكن على الرغم من أنه يمكن تنفيذ عدة أسطر، الا انها ليست مريحة جدا، خصوصا، في تنفيذ  التعليمات البرمجية الكبيرة نوعا ما والمعقدة، لذالك ننصح باستخدام  المسودة Scratchpad كأداة أفضل.

+ +

لفتح المسودة (Shift+F4)، او حدد "المسودة" من القائمة اختر "المطور"، وهي ضمن القائمة في فايرفوكس. ستفتح في نافذة منفصلة، يمكنك استخدامها لكتابة وتنفيذ جافا سكريبت في المتصفح. يمكنك أيضا حفظ النصوص إلى القرص وتحميلها من القرص.

+ +

+ +

مرحبا بالعالم

+ +

لتبدأ بكتابة جافا سكريبت، افتح المسودة واكتب "مرحبا بالعالم". كما يلي:

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

من قائمة "تنفيذ" واضغط على تنفيذ او  Ctrl + R لمشاهدة ناتج الكود في المتصفح الخاص بك!

+ +

في الصفحات التالية، سيعرض هذا الدليل بناء الجملة في لغة جافا سكريبت وميزاتها. وسوف تكون ان شاء الله قادرا على كتابة تطبيقات أكثر تعقيدا.

+
+ +

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

diff --git a/files/ar/web/javascript/guide/loops_and_iteration/index.html b/files/ar/web/javascript/guide/loops_and_iteration/index.html new file mode 100644 index 0000000000..3bc05c57a7 --- /dev/null +++ b/files/ar/web/javascript/guide/loops_and_iteration/index.html @@ -0,0 +1,352 @@ +--- +title: الحلقات والتكرار +slug: Web/JavaScript/Guide/Loops_and_iteration +translation_of: Web/JavaScript/Guide/Loops_and_iteration +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}
+ +

الحلقات، وسيلة سريعة وسهلة لفعل شيئا ما، مرارا وتكرارا. يقدم هذا الفصل من دليل الجافاسكريب  مختلف عبارات التكرار المتاحة لجافا سكريبت.

+ +
+

يمكنك التفكير في الحلقة كنسخة من لعبة في الكمبيوتر، حيث ستقوم بتحريك السوبر ماريو X من الخطوات الى الامام، على سبيل المثال، امر التحريك، " تَحرًك ب 5 خطوات إلى الامام". يمكن تطبيق مثل هذه الفكرة باستخدام الحلقة:

+ +
var step;
+for (step = 0; step < 5; step++) {
+  // Runs 5 times, with values of step 0 through 4.
+  console.log('Walking east one step');
+}
+
+ +

هناك أنواع مختلفة من الحلقات، والمهم هو انها تقوم بشئ واحد: وهو تكرار بعض الاجراءات عدة مرات. الحلقات بمختلف انواعها، تقدم طرقا مختلفة لتحديد نقطة البداية ونقطة النهاية للحلقة. يمكن استخدام نوع معين من الحلقات، لحل نوع معين من المشاكل.

+ +

الحلقات المتوفرة في جافاسكريبت وهي :

+ + + +

الحلقة for

+ +

الحلقة {{jsxref("statements/for","for loop")}} لاتتوقف عن التكرار حتى يتم تحقق الشرط المحدد ب false. الحلقة for لجافاسكريبت مشابه للحلقة for الخاصة ب Java و C. يوضح الشكل التالي التركيبة الاساسية للحلقة for:

+ +
for ([initialExpression]; [condition]; [incrementExpression])
+  statement
+
+ +

عند تنفيذ الحلقة، يحدث ما يلي:

+ +
    +
  1.  initialExpression : التعبير المستخدم لتهيئة الحلقة، سيتم تنفيذه، إذا كان موجوداً. يقوم هذا التعبير بتهيئة عداد حلقة واحدة أو أكثر، من الممكن استخدام تعبيرات أكثر تعقيدا  إذا لزم الأمر. يمكن ايضا أن يتم تعريف المتغيرات في هذا التعبير.
  2. +
  3. condition : تعبير الشرط الذي تتمحور حوله الحلقة. اذا كانت قيمته تساوي true، ستنفذ الحلقة من جديد، عندما ستصبح قيمته تساوي false، ستنتهي الحلقة، إذا تم حذف تعبير الشرط تماما. سيعتبر الشرط صحيحاً true.
  4. +
  5. statement : التعليمة البرمجية التي ستنفذ ما دام الشرط يساوي true. لتنفيذ تعليمات برمجية متعددة، استخد التعليمة بلوك ({ ... }).
  6. +
  7. incrementExpression : تحديث التعبير، إذا كان موجودا، ينفذ، ويعود التحكم إلى الخطوة رقم 2.
  8. +
+ +

مثال

+ +

تحتوي الدالة التالية على التعليمة for التي تقوم باحصاء عدد العناصر options المحددة في العنصر {{HTMLElement("select")}}. التعليمة for تعلن عن المتغير i وتقوم بتهيئته ب 0. وتتحقق من ان i اصغر من عدد العناصر في العنصر <select>. ستنفذ التعليمة if  بنجاح، وستزيد قيمة i بواحد ما دامت الحلقة مستمرة بالتكرار.

+ +
<form name="selectForm">
+  <p>
+    <label for="musicTypes">Choose some music types, then click the button below:</label>
+    <select id="musicTypes" name="musicTypes" multiple="multiple">
+      <option selected="selected">R&B</option>
+      <option>Jazz</option>
+      <option>Blues</option>
+      <option>New Age</option>
+      <option>Classical</option>
+      <option>Opera</option>
+    </select>
+  </p>
+  <p><input id="btn" type="button" value="How many are selected?" /></p>
+</form>
+
+<script>
+function howMany(selectObject) {
+  var numberSelected = 0;
+  for (var i = 0; i < selectObject.options.length; i++) {
+    if (selectObject.options[i].selected) {
+      numberSelected++;
+    }
+  }
+  return numberSelected;
+}
+
+var btn = document.getElementById('btn');
+btn.addEventListener('click', function() {
+  alert('Number of options selected: ' + howMany(document.selectForm.musicTypes));
+});
+</script>
+
+
+ +

الحلقة do...while

+ +

الحلقة {{jsxref("statements/do...while", "do...while")}} لاتتوقف عن التكرار حتى يتم تحقق الشرط المحدد ب false . يوضح الشكل التالي التركيبة الاساسية للحلقة do...while

+ +
do
+  statement
+while (condition);
+
+ +

statement: تنفذ مرة واحدة قبل أن تبدا عملية التحقق من الشرط. عند البدا بعملية التحقق، اذا كان الشرط (condition) يساوي true، تنفذ التعليمة البرمجية (statement) مرة اخرى. بعد انهاء التنفيذ، يتم التحقق مرة اخرى من الشرط. الى ان يصبح الشرط يساوي false، عندها يتوقف التنفيذ ويتم انتقال التحكم الى التعليمة البرمجية التي تلي do...while. لتنفيذ تعليمات برمجية متعددة، استخدم التعليمة بلوك ({ ... }).

+ +

مثال

+ +

في المثال التالي، الحلقة do، تنفذ مرة واحدة على الاقل وتستمر بالتكرار حتى يصبح i ليس أقل من 5.

+ +
var i = 0;
+do {
+  i += 1;
+  console.log(i);
+} while (i < 5);
+ +

الحلقة while

+ +

الحلقة {{jsxref("statements/while","while")}} ستستمر بتنفيذ التعليمة البرمجية المرتبطة بها طالما الشرط المحدد يساوي true. يوضح الشكل التالي التركيبة الاساسية للحلقة while

+ +
while (condition)
+  statement
+
+ +

عندما سيصبح الشرط يساوي false، ستتوقف التعليمة البرمجية (statement) المرتبطة بالحلقة  عن التنفيذ وسينتقل التحكم الى التعليمة البرمجية التي تلي الحلقة while.

+ +

يتم التحقق من شرط الاختبار قبل تنفيذ statement. كلما عاد الشرط ب true، ستنفذ statement ويتم الرجوع الى الشرط للتحقق منه مرة اخرى. عندما سيعود الشرط ب false سيتوقف التنفيذ وسينتقل التحكم الى التعليمة البرمجية التي تلي الحلقة while.  لتنفيذ تعليمات برمجية متعددة، استخدم التعليمة بلوك ({ ... }).

+ +

المثال الاول

+ +

الحلقة while ستستمر بالتكرار طالما n أقل من ثلاثة:

+ +
var n = 0;
+var x = 0;
+while (n < 3) {
+  n++;
+  x += n;
+}
+
+ +

مع كل تكرار، ستقوم الحلقة بالزيادات على n وتضيف قيمته إلى x. لذالك  x و n ستمتلك القيم التالية:

+ + + +

بعد الانتهاء من المرور الثالث، الشرط ( n < 3 ) لم يعد يساوي true، لذالك ستنتهي الحلقة.

+ +

المثال الثاني

+ +

لتجنب تكرار الحلقة الى ما لا نهاية. تأكد من أن الشرط في الحلقة، سيصبح في نهاية المطاف ب false، التعليمة البرمجية في الحلقة while التالية، لن تتوقف عن التنفيذ بسبب ان الشرط لن يصبح ب false:

+ +
while (true) {
+  console.log('Hello, world!');
+}
+ +
+

تحذير: استمرار تكرار الحلقة الى ما لا نهاية سيتسبب في توقف المتصفحات عن العمل.

+
+ +

التعليمة label

+ +

تستخدم التعليمة {{jsxref("statements/label","label")}}  لتوفير معرف (id) للتعليمة البرمجية المراد الرجوع اليها من موقع آخر في البرنامج. على سبيل المثال، يمكنك استخدام label لتحديد حلقة، ثم استخدام التعليمة break او continue للإشارة إلى ما إذا كان البرنامج ينبغي أن يوقف الحلقة أو الاستمرار في تنفيذها.

+ +

التعبير الخاص بالتعليمة  label يشبه ما يلي:

+ +
label :
+   statement
+
+ +

قيمة label  يمكن ان تكون أي معرف جافاسكريبت باستثناء الكلمات المحجوزة. التعليمة البرمجية (statement) التي سيشار اليها من طرف label يمكن ان تكون اي تعليمة برمجية.

+ +

مثال

+ +

في هذا المثال، label markLoop يعرف الحلقة while.

+ +
markLoop:
+while (theMark == true) {
+   doSomething();
+}
+ +
+

ملاحظة: لمزيد من التفاصيل حول التعليمة label، راجع صفحة مرجع الجافا سكريبت

+
+ +

التعليمة break

+ +

تستخدم التعليمة {{jsxref("statements/break","break")}} لانهاء الحلقة، او switch، أو بالتزامن مع االتعليمة label.

+ + + +

يمكن التعبير عن  التعليمة break من خلال طريقتين:

+ +
break;
+break label;
+
+ +

تستخدم الطريقة الأولى لانهاء الحلقة المتواجدة بها، او لانهاء switch. الطريقة الثانية لانهاء تنفيذ التعليمات التي تم تحديدها من قبل label.

+ +

المثال الاول

+ +

يقوم المثال التالي بالتكرار على عناصر المصفوفة، وبمجرد الوصول الى العنصر المحدد في الشرط وهو theValue سيتم انهاء الحلقة،

+ +
for (var i = 0; i < a.length; i++) {
+  if (a[i] == theValue) {
+    break;
+  }
+}
+ +

المثال الثاني

+ +

المثال التالي، يبين كيفية استخدام التعليمة break بكلا الطريقتين:

+ +
var x = 0;
+var z = 0;
+labelCancelLoops: while (true) {
+  console.log('Outer loops: ' + x);
+  x += 1;
+  z = 1;
+  while (true) {
+    console.log('Inner loops: ' + z);
+    z += 1;
+    if (z === 10 && x === 10) {
+      break labelCancelLoops;
+    } else if (z === 10) {
+      break;
+    }
+  }
+}
+
+ +

التعليمة continue

+ +

يمكن استخدام التعليمة {{jsxref("statements/continue","continue")}} لاستئناف الحلقة while) do-while ،for ، مع labe)، بعد توقفها لغرض معين.

+ + + +

يمكن التعبير عن  التعليمة continue من خلال طريقتين:

+ +
continue;
+continue label;
+
+ +

المثال الاول

+ +

في المثال التالي، لدينا الحلقة while مع التعليمة continue التي ستنفذ حينما تصبح i تساوي 3. ولدينا n الذي سيحتوي على القيم التالية:  1, 3, 7 و 12.

+ +
var i = 0;
+var n = 0;
+while (i < 5) {
+  i++;
+  if (i == 3) {
+    continue;
+  }
+  n += i;
+}
+
+ +

المثال الثاني

+ +

التعليمة label checkiandj تحتوي على التعليمة label checkj. عند مصادفة continue سيقوم البرنامج بانهاء التكرار الحالي ل checkj ويبدأ التكرار من جديد. وفي كل مرة يتم مصادفة continue، تستمر checkj بالتكرار حتى يعود الشرط ب false. عندما سيتم العودة ب false،  ما تبقى من التعليمة checkiandj سيكتمل، و checkiandj ستستمر بالتكرار حتى يعود الشرط ب false. عندما سيتم العودة ب false، سينتقل البرنامج الى التعليمة البرمجية التي تلي checkiandj.

+ +
var i = 0;
+var j = 10;
+checkiandj:
+  while (i < 4) {
+    console.log(i);
+    i += 1;
+    checkj:
+      while (j > 4) {
+        console.log(j);
+        j -= 1;
+        if ((j % 2) == 0) {
+          continue checkj;
+        }
+        console.log(j + ' is odd.');
+      }
+      console.log('i = ' + i);
+      console.log('j = ' + j);
+  }
+ +

عموما: التعليمة break تقوم بانهاء الحلقة نهائيا عندما يتم تحقق الشرط المحدد، فيما تقوم التعليمة continue بتوقيف الحلقة للتحقق من الشرط المحدد، وعندما يتم تنفيذ الشرط، يتم استئناف الحلقة.

+ +

التعليمة for...in

+ +

تستخدم الحلقة {{jsxref("statements/for...in","for...in")}} للتكرار على جميع خصائص الكائن القابلة للتكرار enumerable properties.  مقابل كل خاصية مميزة، ستنفذ الجافا سكريبت تعليمات برمجية محددة. يوضح الشكل التالي التركيبة الاساسية للحلقة for...in

+ +
for (variable in object) {
+  statements
+}
+
+ +

مثال

+ +

الدالة التالية تتضمن كائن واسم الكائن كبارامترات لها. تقوم بالتكرار على كل خصائص الكائن وترجع سلسلة نصية بأسماء الخصائص والقيم الخاصة بها.

+ +
function dump_props(obj, obj_name) {
+  var result = '';
+  for (var i in obj) {
+    result += obj_name + '.' + i + ' = ' + obj[i] + '<br>';
+  }
+  result += '<hr>';
+  return result;
+}
+ +

بالنسبة للكائن car مع الخصائص make و model، الناتج سيكون على الشكل التالي:

+ +
car.make = Ford
+car.model = Mustang
+
+ +

for...in و المصفوفات

+ +

على الرغم من كونه مغريا استخدام الحلقة for...in للتكرار على عناصر المصفوفة {{jsxref("Array")}}  الا انها، يمكن أن تقوم بسلوك غير متوقع. في الواقع، الحلقة for...in ستقوم بإرجاع اسماء الخصائص المعرفة من قبل المستخدم بالإضافة إلى الفهارس الرقمية. فمثلا، إذا قمت بالتعديل على Array object، كإضافة خصائص او وظائف جديدة. فستقوم الحلقة for...in بالتكرار على هذه الخصائص او الوظائف بالإضافة إلى عناصر المصفوفة، وبالتالي فمن الأفضل استخدام الحلقة التقليدية {{jsxref("statements/for","for")}} لارجاع الفهارس الرقمية بشكل صحيح عند التكرار على المصفوفة.  يبين المثال التالي كيفية حصول ذالك.

+ +
var myArray = [0, 1, 2, , , 5];
+myArray.foo = "hello";
+
+for (var i in myArray) {
+  	console.log(i);  // Outputs 0, 1, 2, 5, hello.
+}
+
+for (var i = 0; i < myArray.length; ++i) {
+  	console.log(i);  // Outputs 0, 1, 2, 3, 4, 5
+}
+ +

الحلقة for...of

+ +

التعليمة {{jsxref("statements/for...of","for...of")}} نوع جديد من الحلقات تم إضافتها الى الإصدار السادس  من جافا سكربت ، وتستخدم للتكرار على العناصر الموجودة في أي مجموعة أو iterable objects (مثل {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}} والكائن {{jsxref("functions/arguments","arguments")}} الخ.), كما أن هذا الأسلوب يمكننا من تنفيذ تعليمة برمجية معينة على كل عنصر تم جلبه على حدة للتعديل على أي من خصائصه. يوضح الشكل التالي التركيبة الاساسية للحلقة for...of

+ +
for (variable of object) {
+  statement
+}
+ +

المثال التالي، يوضح الفرق بين الحلقة for...of والحلقة  {{jsxref("statements/for...in","for...in")}} الحلقة for...in تقوم بارجاع اسماء الخصائص فيما الحلقة for...of تقوم بارجاع قيم الخصائص:

+ +
let arr = [3, 5, 7];
+arr.foo = 'hello';
+
+for (let i in arr) {
+   console.log(i); // logs "0", "1", "2", "foo"
+}
+
+for (let i of arr) {
+   console.log(i); // logs 3, 5, 7
+}
+
+
+ +

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

diff --git a/files/ar/web/javascript/guide/regular_expressions/index.html b/files/ar/web/javascript/guide/regular_expressions/index.html new file mode 100644 index 0000000000..96928196f8 --- /dev/null +++ b/files/ar/web/javascript/guide/regular_expressions/index.html @@ -0,0 +1,813 @@ +--- +title: التعبيرات القياسية +slug: Web/JavaScript/Guide/Regular_Expressions +translation_of: Web/JavaScript/Guide/Regular_Expressions +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}
+ +

التعبيرات القياسية (Regular Expressions)، هي أنماط (patterns) تُستخدم لمطابقة مجموعة من الأحرف في السلاسل النصية. التعبيرات القياسية في جافاسكربت كائنات أيضا. تُستخدم هذه الأنماط مع الوظائف {{jsxref("RegExp.exec", "exec")}} و{{jsxref("RegExp.test", "test")}} للكائن {{jsxref("RegExp")}}، ومع الوظائف {{jsxref("String.match", "match")}}، و {{jsxref("String.replace", "replace")}}، و{{jsxref("String.search", "search")}} و {{jsxref("String.split", "split")}} للكائن {{jsxref("String")}}. يتناول هذا الفصل  تعبيرات جافاسكربت القياسية.

+ +
+

انشاء تعبير قياسي او ريجكس

+ +

يمكنك انشاء ريجكس من خلال احدى الطرق التالية:

+ +

الطريقة الاولى، باستخدام التعبير القياسى الحرفي regular expression literal، ويتضمن الباترن pattern بين سلاشين، كما يلي:

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

يقوم ال Regular expression literals بتجهيز التعبير القياسي عند تحميل السكريبت. شرط ان يظل التعبير القياسي ثابتا، في هذه الحالة، استخدام هذا الشكل المختصر يمكن أن يحسن من الأداء.

+ +

الطريقة الثانية، من خلال استدعاء constructor الكائن RegExp، كما يلي:

+ +
var re = new RegExp('ab+c');
+ +

استخدام ال constructor، يقلل من وقت تشغيل الريجكس. إسْتخدِم ال  constructor عندما تريد ان يكون الريجكس قابلا للتغيير، او في حالة عدم علمك بالريجكس الذي ستحصل عليه من طرف اخر. كحقل المدخلات مثلا.

+ +

انشاء باترن الريجكس

+ +

يتكون الباترن البسيط اما من رموز عادية، مثل /abc/، او خليط من الرموز العادية والرموز الخاصة، مثل /ab*c/ او /Chapter (\d+)\.\d*/. يحتوي هذا الباترن على اقواس هلالية، هذه الاقواس ستقوم بدور ذاكرة الجهاز، بحيث ستقوم بتخزين قيمة المطابقة الناتجة عن هذا الجزء من الباترن وفهرستها ليتم استدعاؤها لاحقا. للمزيد من التفاصيل حول مطابقة السلسلة النصية الجزئية بين قوسين.

+ +

استخدام الباتر البسيط

+ +

تتكون الباترنز البسيطة، من رموز صريحة ومباشرة، تصف فيها ما تريد مقارنته مباشرة. مثلا، الباترن /abc/ سيطابق مجموعة من الرموز في سلسلة نصية، شرط تواجد هذه الرموز جنبا الى جنب بشكل مرتب. لذالك، ستنجح المطابقة في هذه السلسلة النصية "Hi, do you know your abc's?"  وكذالك في السلسلة النصية التالية "The latest airplane designs evolved from slabcraft."، نجحت المطابقة في كلتا الحالتين لان السلسلة الفرعية 'abc' هي المطلوبة. وهذا لايتطابق مع هذه السلسلة النصية 'Grab crab' لانها تحتوي على سلسلة نصية غير تلك المطلوبة  'ab c'.

+ +

استخدام الرموز الخاصة

+ +

عندما يتطلب الامر عملية بحث، أكثر من مطابقة صريحة ومباشرة، مثل البحث عن واحد او اكثر من ال 'b'، او البحث عن مسافة فارغة، عندها سيتوجب على الباترن ان يحتوي على الرموز الخاصة. مثلا، الباترن /ab*c/ سيطابق مجموعة من الرموز، حيث ستكون 'a' متبوعة بصفر او اكثر من ال 'b'، الرمز الخاص نجمة * يرصد وجود العنصر المطلوب صفر او اكثر من المرات، متبوعا مباشرة ب 'c'. بعد فحص السلسلة النصية "cbbabbbbcdebc," قام الباترن بمطابقة السلسلة الجزئية 'abbbbc'.

+ +

يحتوي الجدول التالي على قائمة مكتملة من رموز الريجكس الخاصة وشرحها.

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

الرموز الخاصة بالريجكس.

+
الرمزشرح الاستخدام
\ +

 

+ +

مطابقات وفقا للقواعد التالية:
+
+ الباكسلاش الذي يسبق الرمز العادي يشير الى ان الرمز التالي هو رمز من الرموز الخاصة ولا ينبغي تفسيره حرفيا. مثلا 'b' من دون باكسلاش \ ، ستطابق 'b' بحروف صغيرة. لكن \b في حد داتها لا تطابق اي حرف، لانها من الرموز الخاصة وتعني حصر او تحديد حدود للرموز المطلوبة word boundary character.
+
+ الباكسلاش الذي يسبق الرموز الخاصة، يشير الى ان الرمز التالي هو ليس من الرموز الخاصة وينبغي تفسيره حرفيا. مثلا، الباترن /a*/ يحتوي على احد الرموز الخاصة * وهو لمطابقة صفر او اكثر من a، بعد اضافة الباكسلاش له، كما في  الباترن /a\*/ تم الغاء رمزيتة، وبالتالي اصبح الباترن  /a\*/ يطابق السلسلة الحرفية 'a*'.
+
+ لا تنس تهريب الباكسلاش نفسه، بينما تستخدم الكونستراكتر RegExp( "\\s", "g" )، لانه يعمل ايضا، كمهرب للرموز الخاصة في السلسلة النصية.

+ +

 

+
^ +

 

+ +

مطابقة بداية المدخلات. ادا كان البند multiline ب true، اي ان m موجودة في الباترن /^a/gm سيبدا البحث عن المطابقة في بداية اي سطر جديد.
+
+ مثلا الباترن  /^a/gm  سيطابق اثنان من 'a'، في "a special char\nacter"، لاحظ وجود السطر الجديد \n في السلسلة النصية.
+
+ الرمز ^ سيصبح له معنى اخر عندما يستخدم مع المجموعة. توجه الى مجموعة الرموز لمعرفة المزيد من التفاصيل.

+ +

 

+
$ +

 

+ +

مطابقة نهاية المدخلات. ادا كان البند multiline  ب true، اي ان m موجودة في الباترن /r$/gm سيبدا البحث عن المطابقة في نهاية اي سطر جديد.
+
+ مثلا الباترن /r$/gm سيطابق اثنان من 'r'، في "a special char\nacter"، لاحظ وجود السطر الجديد \n في السلسلة النصية.

+
* +

 

+ +

مطابقة التعبير الذي سيسبق الرمز * صفر او اكثر من المرات، وهو مكافئ ل {0,}.

+ +

مثلا، /bo*/ سيطابق 'boooo' في "A ghost booooed" و 'b' في "A bird warbled" لكن لا شئ بالنسبة ل "A goat grunted".

+ +

 

+
+ +

 

+ +

مطابقة التعبير الذي سيسبق الرمز + مرة واحدة على الاقل او اكثر من المرات، وهو مكافئ ل {1,}.

+ +

مثلا، /a+/ ستطابق 'a' في "candy" ومجموعة ال  'a' في "caaaaaaandy" لكن لا شئ بالنسبة ل "cndy".

+ +

 

+
? +

 

+ +

مطابقة التعبير الذي سيسبق الرمز ? صفر او واحد من المرات، وهو مكافئ ل {0,1}.
+
+ مثلا، الباترن /e?le?/ سيطابق 'el' في "angel" و 'le' في "angle" وكذالك 'l' في "also".
+
+ اذا استخدم الرمز ? مباشرة بعد احد هذه المحددات *، +، ?، او {}، سيؤثر على سلوكها الافتراضي، فيجعلها غير طماعة non-greedy او غير جشعة (تطابق عدد محدود من الاحرف) بخلاف سلوكها الافتراضي، وهو التصرف بجشع (تطابق اكثر عدد ممكن من الاحرف)، مثلا، باستخدام الباترن الجشع، /\d+/ ستطابق كل السلسلة "123" في "123abc" . اما باستخدام الباترن الغير جشع، /\d+?/ وعلى نفس السلسلة ستطابق "1" فقط.
+
+ مثال اكثر دقة حول non-greedy و greedy، فرضا، نريد مطابقة تاجات الاتش تي ام ال، باستخدام الباترن الجشع /<(.+)>/g سيتم مطابقة كل السلسلة النصية "<div>fCh<p>elema</p>lCh</div>"، اما باستخدام الباترن الغير شجع /<(.+?)>/g فسيتم مطابقة التاجات ومحتواها فقط. بمعنى، ان العملية ستسير بالشكل التالي: مع بداية البحث، عندما سيجد التاج الاول '<div>' سييكتفي به ولا يطمع في ما يليه، ثم ينتقل مباشرة نحو الهدف الثاني '<p>' فيطابقه ويكتفي به دون ان يطمع في ما يليه، وهكذا. مع العلم ان الباترن عبارة عن البحث (.+?) في كل شئ، لكن من دون طمع.
+ الرمز ? يصبح له معنى اخر مع lookahead assertions، النظر الى الامام x(?=y) ومنع النظر الى الامام x(?!y) سيتم شرحها في هذا الجدول.

+ +

 

+
. +

 

+ +

النقطة الكسرية تطابق اي شئ، ما عدا السطر الجديد

+ +

مثلا، /.n/ ستطابق 'an' و 'on' في "nay, an apple is on the tree", لكن ليس 'nay'.

+ +

 

+
(x) +

 

+ +

مطابقة 'x' وانشاء فهرسة جزئية. كما يبين المثال التالى. اقواس المجموعة المفهرسة تسمى capturing parentheses.
+
+ مثلا،'(foo)' و '(bar)' في الباترن /(foo) (bar) \1 \2/ تطابق وتفهرس الكلمة الاولى والكلمة الثانية في السلسلة الحرفية "foo bar foo bar". والفهرسة الرقمية \1 و \2  تولد الكلمة الثالثة والكلمة الرابعة بناءا على الاقواس المحيطة بكل منهما. تذكر ان هذه الفهرسة الرقمية تستخدم داخل الباترن فقط. فيما تستخدم المتغيرات السحررية $1, $2, ..., $n خارج الباترن، وتستخدم في عملية الاستبدال فقط، مثلا، 'bar foo'.replace(/(...) (...)/, '$2 $1').  $& يطابق هذا المتغير السحري $& السلسلة النصية بالكامل، او بمعنى اصح، ينقل ناتج الباترن بالكامل.

+ +

 

+
(x:?) +

 

+ +

مطابقة ال 'x' لكن دون انشاء جزئية مفهرسة، اقواس المجموعة هنا تسمى non-capturing parentheses

+ +

انشاء جزئية مفهرسة وعدم استخدامها، يبطئ من سرعة محرك الريجكس، لانه يتسبب له في عمل زائد، يمكنك جعل محرك الريجكس اسرع قليلا باستخدام non-capturing.

+ +

علامة الاستفهام والنقطتين بعد قوس الافتتاح هما من الرموز الخاصة، استخدامهما جنبا الى جنب يخبر محرك الريجكس بان هذه المجموعة لا ينبغي ان تعامل كجزئية مفهرسة. وبالتالي لا يمكن، استدعاء المطابقة من خلال الفهرسة الرقمية\1... او عناصر المصفوفة [1]... او اعادة استخدام المطابقة من خلال المتغيرات السحرية $1...$9.

+ +

 

+
=? +

 

+ +

مطابقة ال 'x' فقط اذا كانت 'x' متبوعة ب 'y'. وهذا يسمى النظر الى الامام lookahead.

+ +

مثلا، /Jack(?=Sprat)/ سيطابق 'Jack' فقط اذا كان متبوعا ب 'Sprat'. وكذالك بالنسبة ل /Jack(?=Sprat|Frost)/ سيطابق 'Jack' فقط اذا كان متبوعا ب 'Sprat' او 'Frost'. ومع ذالك، لا 'Sprat' ولا 'Frost' جزء من ناتج المطابقة.

+ +

 

+
!? +

 

+ +

مطابقة ال 'x' فقط اذا كانت 'x' غير متبوعة ب 'y'. وهذا يسمى منع او ابطال النظر الى الامام negated lookahead.

+ +

مثلا، /\d+(?!\.)/ سيطابق عدد فقط اذا كان غير متبوعا بفاصلة كسرية. الريجكس /\d+(?!\.)/.exec("3.141") سيطابق '141' لكن لن يطابق '3.141'.

+ +

 

+
x|y +

 

+ +

مطابقة 'x' أو 'y'.

+ +

مثلا، /green|red/ سيطابق 'green' في "green apple" و 'red' في "red apple.".

+ +

 

+
{n} +

 

+ +

مطابقة n تحديدا، بناءا على التعبير الذي سيسبقه. n يجب ان يكون عددا صحيحا.
+
+ مثلا، /a{2}/ لن يطابق 'a'في "candy," لكنه سيطابق جميع ال a في "caandy," كما سيطابق اثنان من ال a الاولى في "caaandy.".

+ +

 

+
{n,} +

 

+ +

مطابقة n او اكثر، بناءا على التعبير الذي سيسبقه. n يجب ان يكون عددا صحيحا.

+ +

مثلا، /a{2,}/ سيطابق "aa" ، "aaaa" و "aaaaa" لكن ليس "a".

+ +

 

+
{n,m} +

 

+ +

حيث ان n و m من الاعداد الصحيحة الموجبة، و n <= m. فستكون المطابقة من n الى m، بناءا على التعبير الذي سيسبقها.

+ +

مثلا، /a{1,3}/ لن يطابق شئ في "cndy" لكنه سيطابق 'a' في "candy," وكذاك اثنان من ال 'a' الاولى في "caandy," وايضا الثلاثة "a" الاولى في "caaaaaaandy". لاحظ عند مطابقة "caaaaaaandy" تم مطابقة "aaa" فقط، بالرغم من احتواء السلسة النصية على اكثر من ذالك.

+ +

 

+
[xyz] +

 

+ +

المجموعة، او مجموعة الرموز، هذا النوع من الباترن يطابق اي رموز داخل الاقواس المعقوفة، بما فيها المهربات المتتالية escape sequences. الرموز الخاصة مثل النقطة (.) والنجمة (*) تصبح رموز عادية شانها شان اي حرف في سلسلة نصية، لذالك فهي لا تحتاج لباكسلاش. يمكنك تحديد منظم الرموز وفصله بشرطة، كما يبين المثال التالي:
+
+ الباترن [a-d] سيطابق نفس ما سيطابقه الباترن [abcd] سيطابقان 'b' في "brisket" و 'c' في "city". وكذالك بالنسبة للباترن /[a-z.]+/ و /[\w.]+/ بامكانهما مطابقة كامل السلسلة النصية "test.i.ng".

+ +

 

+
[xyz^] +

 

+ +

منع مجموعة من الرموز او رموز معينة. سيتم مطابقة اي شئ ما عد ما ورد داخل الاقواس المعقوفة، يمكنك تحديد منظم الرموز وفصله بشرطة، جميع ما يمكن استخدامه في المجموعة او مجموعة الرموز العادية يمكن استخدامه هنا.

+ +

مثلا، الباترن [^abc] هو نفسه [^a-c]. سيطابقان 'r' في "brisket" و 'h' في "chop."

+ +

 

+
[b\] +

 

+ +

سيطابق backspace (U+0008). اذا كنت ترغب بمطابقة الرمز النصي: رجوع الى الخلف literal backspace character. فمن الضروري استخدام الاقواس المعقوفة، حتى لا تتعارض مع \b.

+ +

 

+
b\ +

 

+ +

مطابقة حدود الكلمة word boundary.

+ +

\b، ستطابق الكلمة التي لايسبقها ولا يليها اي من، ما ورد في هذه المجموعة [A-Za-z0-9_] او في مثيلتها \w، بمعنى ادق، ستقبل بوجود المسافة الفارغة والرموز النصية الخاصة مثل "&=)é'?*-" ، اي، كل ما يمكن ان ينتج عن هذه المجموعة [^A-Za-z0-9_] او عن مثيلتها \W، اما من قبل او من بعد المطابقة، او من كلا الجانبين، او ان تكون في بداية السلسلة او نهايتها. لاحظ ان ال \b ليست جزءا من المطابقة. بل للدلالة فقط. وايضا لا تتعارض مع [\b].

+ +

امثلة مختلفة:
+
+ /\bm/ ستطابق 'm' في "moon".
+ /oo\b/ لن تطابق 'oo' في "moon" لان 'oo' متبوعة بالكلمة الرمزية 'n'.
+ /oon\b/ ستطابق 'oon' في "moon"، لان 'oon' هو نهاية السلسلة النصية، وبالتالي ليست متبوعة باية كلمة رمزية.
+ /\w\b\w/ لن يطابق اي شئ، لان \w لايمكنها ابدا ان تكون متبوعة ب \b و \w.

+ +
+

ملاحظة: محرك الريجكس في الجافاسكريبت حدد بالتدقيق مجموعة الرموز على ان تكون "كلمات" رمزية. أي حرف ليس في تلك المجموعة يعتبر كلمة مكسورة. هذه المجموعة من الأحرف محدودة إلى حد ما: وهي تتألف فقط من الأبجدية الرومانية في كلتا الحروف الصغيرة والحروف الكبيرة، والاعداد العشرية، والرمز underscore. الحروف المعلمة مثل "é" او "ü" ، لسوء الحظ عوملت ككلمات مكسورة.

+ +

 

+
+
B\ +

 

+ +

ال non-word boundary\B. عكس ما يمكن لل \b ان تقوم به.

+ +

مثلا، /\B../ ستطابق 'oo' في "noonday"، /y\B./ ستطابق 'ye' في "possibly yesterday".

+ +

 

+
cX\ +

 

+ +

حيث ان X هو منظم الرموز من A الى Z. يطابق رمز عنصر التحكم في سلسلة نصية. مثلا،

+ +

مثلا، /\cM/ سيطابق control-M (U+000D) في السلسلة النصية.

+ +

 

+
d\ +

 

+ +

مطابقة الاعداد. ويكافئ الباترن [0-9].

+ +

مثلا، /\d/ او /[0-9]/ ستطابق '2' في "B2 is the suite number.".

+ +

 

+
D\ +

 

+ +

مطابقة كل شئ ما عدا الاعداد. ويكافئ الباترن [^0-9].

+ +

مثلا، /\D/ او /[^0-9]/ سيطابق 'B' في "B2 is the suite number.".

+ +

 

+
f\سيطابق نموذج التلقيم form feed (U+000C).
n\سيطابق سطر التلقيم line feed (U+000A).
r\ +

سيطابق carriage return (U+000D).

+
s\ +

 

+ +

مطابقة رمز المسافة الفارغة، بما في ذالك المسافة، التاب، نمودج التلقيم، سطر التلقيم، ويكافئ [ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

+ +

مثلا، /\s\w*/ سيطابق ' bar' في "foo bar."

+ +

 

+
S\ +

 

+ +

مطابقة اي شئ ما عدا رمز المسافة الفارغة، ويكافئ [^ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

+ +

مثلا، /\S*/ سيطابق 'foo' في "foo bar."

+ +

 

+
t\سيطابق tab (U+0009).
v\ +

سيطابق vertical tab (U+000B).

+
w\ +

 

+ +

مطابقة الحروف الابجدية بما في ذالك ال underscore. ويكافي [A-Za-z0-9_].

+ +

مثلا، /\w/ سيطابق 'a'في "apple," و '5' في "$5.28," و '3' في "3D."

+
W\ +

 

+ +

مطابقة اي شئ غير الحروف الابجدية والاندرسكور، ويكافئ [^A-Za-z0-9_].

+ +

مثلا، /\W/ او /[^A-Za-z0-9_]/ سيطابق '%' في "50%.".

+ +

 

+
n\ +

 

+ +

حيث ان n عدد صحيح موجب، سيشير الى المجموعة المفهرسة capturing parentheses .

+ +

مثلا، /apple(,)\sorange\1/ سيطابق 'apple, orange,' في "apple, orange, cherry, peach.".

+ +

 

+
0\ +

 

+ +

مطابقة الرمز NULL (U+0000). لا تتبع هذا برقم آخر، بسبب ان \0<digits> هو تسلسل التهريب الثماني استخدم \x00 بدلا منه.

+ +

 

+
xhh\مطابقة الرمز مع الكود hh (two hexadecimal digits).
uhhhh\مطابقة الرمز مع الكود hhhh (four hexadecimal digits).
u{hhhh}( فقط عندما يستخدم u flag ) سيطابق الرمز مع ال Unicode بالقيمة hhhh (hexadecimal digits).
+ +

  لتهريب تعابير الريجكس في المدخلات النصية، يمكنك  استخدام دالة الاستبدال التالية:

+ +
function escapeRegExp(string) {
+  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
+}
+ +

يستخدم البند g بعد الباترن، لاجراء بحث عام، ينظر في كل السلسلة النصية ويعود بكل المطابقات. تم شرحه بالتفصيل ادناه. البحث المتقدم باستخدام البنود.

+ +

استخدام الاقواس

+ +

الاقواس المحيطة باي جزء من الباترن، تجعل هذا الجزء قابل للتخزين والفهرسة. بمجرد ما يتم تخزينه وفهرسته، يصبح قابلا لاعادة الاستخدام من اطراف اخرى، كما تم شرحه في استخدام مطابقة الاقواس الجزئية.

+ +

مثلا، الباترن /Chapter (\d+)\.\d*/ يطابق بدقة، الرموز 'Chapter ' متبوعة بواحد او اكثر من الارقام (\d تشير الى اي رقم و + تشير الى واحد او اكثر من المرات، بالاضافة الى الاقواس المستخدمة خصيصا لتخزين وفهرسة ما سينتج عنه )، متبوعا بنقطة او فاصلة عشرية التي هي نفسها من الرموز الخاصة، يسبقها الباكسلاش \ الذي بدوه يخبر الباترن بان يعاملها كنقطة عادية، متبوعا باي رقم يكرر صفر او اكثر من المرات (\d تشير الى اي رقم والنجمة * تشير الى صفر او اكثر من المرات).

+ +

هذا الباترن سيطابق "Chapter 4.3" في "Open Chapter 4.3, paragraph 6"، وايضا سيقوم بتخزين وفهرسة الجزئية '4'. بينما الباترن لا يطابق شئ في "Chapter 3 and 4" بسبب ان السلسلة الحرفية لاتحتوي على النقطة بعد الرقم '3'.

+ +

لمطابقة سلسلة فرعية من دون التسبب في فهرسة الجزء المتطابق (راجع non-capturing)، ضمن الاقواس ابدا الباترن ب ?:. مثلا (?:\d+) ستطابق واحد او اكثر من الارقام من دون ان تفهرس الرموز المتطابقة.

+ +

العمل مع الريجكس

+ +

تستخدم التعابير القياسية مع اثنين من الاوبجكت. الاوبجكت الاول هو RegExp ويحتوي على الوظيفتين test و exec والاوبجكت الثاني وهو String ويحتوي على الوظائف التالية: match، replace، search، و split.  تم شرح هذه الوظائف بالتفصيل في JavaScript reference.

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

الوظائف المملوكة للكائن RegExp

+
الوظيفةوصفها
exec تقوم هذه الوظيفة بتنفيذ بحث لمطابقة سلسلة نصية. وتعود بمصفوفة تحتوي على نتيجة البحث، او تعود ب null في حالة عدم المطابقة.
test تقوم هذه الوظيفة بعمل فحص لمطابقة سلسلة نصية. وتعود اما ب true او false.
match تقوم هذه الوظيفة بتنفيذ بحث لمطابقة سلسلة نصية. وتعود بمصفوفة تحتوي على نتيجة البحث، او تعود ب null في حالة عدم المطابقة. (نفس ما تقوم به الوظيفة exec).
search تقوم هذه الوظيفة بعمل فحص لمطابقة سلسلة نصية. وتعود برقم المكان الذي يتواجد فيه ما تمت مطابقته. او ب -1 في حالة لم يتم العثور على المطلوب.
replace تقوم هذه الوظيفة بتنفيذ بحث لمطابقة سلسلة نصية. ويحل محل السلسلة الجزئية المتطابقة، السلسلة الجزئية البديلة.
split هذه الوظيفة تستخدم الريجكس او سلسلة نصية ثابتة لتقسيم السلسلة الى مصفوفة من السلاسل الجزئية.
+ +

عندما تريد معرفة ما اذا كان الباترن موجود في سلسلة نصية ام لا، استخدم اما الوظيفة test او الوظيفة search ، اما لمعرفة المزيد من المعلومات (ولكن أبطأ قليلا في التنفيذ)، استخدم اما الوظيفة exec او الوظيفة match اذا استخدمت exec او match ونجحت المطابقة، فان هاتان الوظيفتان ستعود بمصفوفة، وفي نفس الوقت ستقوم بتحديث خصائص الريجكس المرتبطة به وكذلك خصائص الريجكس RegExp. اذا فشلت المطابقة, ستعود الوظيفة exec ب null ( التي تفرض : false).

+ +

في المثال التالي، السكريبت يستخدم الوظيفة exec للبحث عن مطابقة في السلسلة النصية:

+ +
var myRe = /d(b+)d/g;
+var myArray = myRe.exec('cdbbdbsbz');
+ +

إذا كنت لا تحتاج إلى الوصول إلى خصائص الريجكس، هناك طريقة بديلة لإنشاء myArray، كالتلي:

+ +
var myArray = /d(b+)d/g.exec('cdbbdbsbz'); // similar to "cdbbdbsbz".match(/d(b+)d/g); however,
+    // the latter outputs Array [ "dbbd" ], while
+    // /d(b+)d/g.exec('cdbbdbsbz') outputs Array [ "dbbd", "bb" ].
+    // See below for further info (CTRL+F "The behavior associated with the".)
+ +

إذا كنت ترغب في بناء ريجكس من سلسلة نصية، هناك بديل آخر، كالتالي:

+ +
var myRe = new RegExp('d(b+)d', 'g');
+var myArray = myRe.exec('cdbbdbsbz');
+ +

مع هذا السكريبت، تنجح المطابقة، ويتم ارجاع مصفوفة وتحديث الخصائص معروض في الجدول التالي.

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

نتائج تنفيذ الريجكس

+
الكائنالخاصية او الفهرسالوصففي هذا المثال
myArray السلسلة النصية التي جرى مطابقتها وجميع السلاسل النصية الجزئية المفهرسة.['dbbd', 'bb', index: 1, input: 'cdbbdbsbz']
indexفهرس بداية المُطابَقة في السلسلة النصية، والفهرسة تبتدئ من 0.1
inputالسلسلة النصية الأصلية."cdbbdbsbz"
[0]الرموز الاخيرة التي جرى مطابقتها"dbbd"
myRelastIndexالفهرس الذي ستبدأ عنده عملية البحث عن المطابقة التالية. وإذا لم يتم ضبط البند "g" فستبقى قيمته مساويةً للصفر. للمزيد حول البحث المتقدم باستخدام البنود.5
sourceنص الباترن. تم تحديثه في الوقت الذي تم فيه إنشاء الريجكس، وليس وقت تنفيذه."d(b+)d"
+ +

كما شاهدنا في المثال الثاني، تستطيع استخدام ريجكس منشا من خلال معد الاوبجكت "object initializer"، من دون اسناده الى متغير. اذا قمت بعمل ذالك، كل ما سيحدث هو ظهور ريجكس جديد. لهذا السبب، لا يمكن الوصول الى خصائص الريجكس. يوضح المثال التالي كيفية الوصول الى خصائص الكائن بالطريقة الصحيحة:

+ +
var myRe = /d(b+)d/g;
+var myArray = myRe.exec('cdbbdbsbz');
+console.log('The value of lastIndex is ' + myRe.lastIndex);
+
+// "The value of lastIndex is 5"
+ +

بينما يوضح المثال التالي كيفية الوصول الى خصائص الكائن بالطريقة الخاطئة:

+ +
var myArray = /d(b+)d/g.exec('cdbbdbsbz');
+console.log('The value of lastIndex is ' + /d(b+)d/g.lastIndex);
+
+// "The value of lastIndex is 0"
+ +

حاصل الباترن /d(b+)d/g في كلتا التعليمات البرمجية، عبارة عن كائنان مختلفان، لذالك هما مختلفان في قيمة الخاصية lastIndex اذا كنت ترغب في الوصول الى خصائص الريجكس المنشا من طرف معد او مهيئ الاوبجكت، يلزمك اولا اسناده لمتغير.

+ +

Using parenthesized substring matches

+ +

بمجرد تضمين جزء من الباترن داخل الاقواس الهلالية، سيصبح جزءا مفهرسا قابل لاعادة الاستخدام، مثلا،  الباترن /a(b)c/ سيطابق 'abc' في  "abcd" ويفهرس المطابقة الجزئية (b) برقم 1، ناتج المطابقة الجزئية (b) هو السلسلة الحرفية الجزئية 'b'. لاستدعاء هذا الجزء المفهرس خارج الباترن، استخدم عناصر المصفوفة [1].... ولاعادة استخدامها داخل الباترن استخدم الفهرسة الرقمية \1 ....
+ - كيفية استدعائها خارج الباترن:

+ +
var myRe = /a(b)c/;
+var myArray = myRe.exec('abcb');
+console.log('The result of submatch N1: ' + myArray[1] );
+
+// log: The result of submatch N1: b
+ +

يمكنك استخدام عدد لا متناهي من هذه الاجزاء المفهرسة، تبتدئ الفهرسة من واحد، عائد المصفوفة سيتضمن جميع الاجزاء المفهرسة في الباترن.
+ كيفية اعادة استخدامها داخل الباترن:

+ +
var myRe = /a(b)c\s\1/g;
+var myArray = myRe.exec('abc b');
+console.log('The result of submatch N1: ' + myArray[1] );
+
+// log: The result of submatch N1: b
+ +

يستخدم السكريبت التالي الوظيفة ()replace لعكس الكلمتين John و Smith في السلسلة النصية 'John Smith'. ويستخدم في نص الاستبدال، المتغيرات السحرية $1 و $2 لاستدعاء المطابقة الجزئية المفهرسة الاولى والثانية. مثال:

+ +
var re = /(\w+)\s(\w+)/;
+var str = 'John Smith';
+var newstr = str.replace(re, '$2, $1');
+console.log(newstr);
+
+// "Smith, John"
+ +
+

ملاحظة: يسمح باستخدام المتغيرات السحرية، 9 مرات فقط، في العملية الواحدة.

+
+ +

البحث المتقدم باستخدام البنود

+ +

التعبيرات القياسية في الجافاسكريبت لها خمسة بنود ، وجودها اختياريا، تسمح لنا بعمل بحثا عاما او بحثا دون مراعات لحالة الاحرف. يمكن استخدامها اما منفردة او مجتمعة وكذالك في اي ترتيب، حسب الطلب، وهي جزء من الريجكس.

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

بنود الريجكس

+
FlagDescription
gبحث عام، عدم وجوده = النتيجة الاولى فقط.
iعدم مراعاة حالة الاحرف، سواء كانت صغيرة او كبيرة.
mالبحث في السطور المتعدد = كامل النص.
uسلسلة يونيكود، أي معاملة الباترن على أنه سلسلة من رموز يونيكود (Unicode code points).
yالمطابقة ستبدأ من الفهرس المُشار إليه بالخاصية lastIndex لكائن التعابير النمطية في السلسلة الهدف، ولن تتم محاولة مطابقة ما قبل هذا الفهرس. للمزيد من المعلومات sticky
+ +

لتضمين بند مع الريجكس استخدم التعبير التالي:

+ +
var re = /pattern/flags;
+ +

او

+ +
var re = new RegExp('pattern', 'flags');
+ +

البنود، جزء لا يتجزأ من الريجكس. لا يمكن إزالتها أو إضافتها لاحقا.

+ +

مثلا، re = /\w+\s/g يقوم بانشاء ريجكس يبحث على واحد او اكثر من الرموز متبوعة بمسافة واحدة، يقوم بتنفيذ هذا الاجراء على السلسلة الحرفية (كاملة = g):

+ +
var re = /\w+\s/g;
+var str = 'fee fi fo fum';
+var myArray = str.match(re);
+console.log(myArray);
+
+// ["fee ", "fi ", "fo "]
+ +

يمكنك استبدال هذا السطر:

+ +
var re = /\w+\s/g;
+ +

ب:

+ +
var re = new RegExp('\\w+\\s', 'g');
+ +

وستحصل على نفس النتيجة.

+ +

يستخدم  البند m لاخبار محرك الريجكس، بان المدخلات النصية، المتعددة السطور، يجب ان تعامل كسطور متعددة. اذا تم استخدام البند m فسيتطابق الرمزان الخاصان ^ و $ ، مع بداية أو نهاية كل سطر من المدخلات، بدلا من المدخل بالكامل. مثال:

+ +
var re = /^Multi\s*line$/gm;
+var str = 'Multi line\n or \nMultiline';
+var myArray = str.match( re );
+
+console.log( myArray );
+// log: [ "Multi line", "Multiline" ]
+ +

 

+ +

امثلة

+ +

تبين الامثلة التالية بعض استخدامات الريجكس

+ +

اعادة صياغة المدخلات النصية.

+ +

يوضح المثال التالي كيف يمكن للريجكس ان يتلاعب في بنية السلسلة النصية، وايضا كيفية استخدام ()string.split و ()string.replace. سيقوم السكريبت التالي بتنظيف واعادة صياغة السلسلة النصية، التي تحتوي على اسماء مفصولة بمسافات فارغة، تابات، وبالظبط فاصلة منقوطة واحدة. واخيرا سيقوم بعكس هذه الاسماء وترتيبها من a الى z.

+ +
// The name string contains multiple spaces and tabs,
+// and may have multiple spaces between first and last names.
+var names = 'Orange Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand ';
+
+var output = ['---------- Original String\n', names + '\n'];
+
+// Prepare two regular expression patterns and array storage.
+// Split the string into array elements.
+
+// pattern: possible white space then semicolon then possible white space
+var pattern = /\s*;\s*/;
+
+// Break the string into pieces separated by the pattern above and
+// store the pieces in an array called nameList
+var nameList = names.split(pattern);
+
+// new pattern: one or more characters then spaces then characters.
+// Use parentheses to "memorize" portions of the pattern.
+// The memorized portions are referred to later.
+pattern = /(\w+)\s+(\w+)/;
+
+// Below is the new array for holding names being processed.
+var bySurnameList = [];
+
+// Display the name array and populate the new array
+// with comma-separated names, last first.
+//
+// The replace method removes anything matching the pattern
+// and replaces it with the memorized string—the second memorized portion
+// followed by a comma, a space and the first memorized portion.
+//
+// The variables $1 and $2 refer to the portions
+// memorized while matching the pattern.
+
+output.push('---------- After Split by Regular Expression');
+
+var i, len;
+for (i = 0, len = nameList.length; i < len; i++) {
+  output.push(nameList[i]);
+  bySurnameList[i] = nameList[i].replace(pattern, '$2, $1');
+}
+
+// Display the new array.
+output.push('---------- Names Reversed');
+for (i = 0, len = bySurnameList.length; i < len; i++) {
+  output.push(bySurnameList[i]);
+}
+
+// Sort by last name, then display the sorted array.
+bySurnameList.sort();
+output.push('---------- Sorted');
+for (i = 0, len = bySurnameList.length; i < len; i++) {
+  output.push(bySurnameList[i]);
+}
+
+output.push('---------- End');
+
+console.log(output.join('\n'));
+ +

استخدام الرموز الخاصة للتحقق من صحة المدخلات.

+ +

في المثال التالي، يتوقع من المستخدم ادخال رقم الهاتف. عندما سينقر المستخدم على زر "الفحص" سيقوم السكريبت بفحص صحة الرقم. اذا كان الرقم صحيحا، سيقوم السكريبت باظهار رسالة تشكر المستخدم وتظهر الرقم المدخل. اذا كان الرقم غير صحيح، سيقوم السكريبت باخبار المستخدم بان الرقم المدخل غير صحيح.

+ +

بعد non-capturing parentheses (?: سينظر الريجكس الى الثلاثة ارقام \d{3} او | الى القوس اليساري \( متبوعا بثلاثة ارقام \d{3} متبوعة بقوس الاغلاق \), (نهاية non-capturing parenthesis ))، متبوعة بشرطة واحدة تليها الباكسلاش او النقطة الكسرية، اذا وجدت قم بفهرستها ([-\/\.])، متبوعة بثلاث ارقام \d{3}، متبوعة باستدعاء الجزء المفهرس \1, متبوعا باربعة ارقام \d{4}.

+ +

يتم تنشيط حدث التغيير عندما يقوم المستخدم بالضغط على إنتر وملأ القيمة RegExp.input.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+    <meta http-equiv="Content-Script-Type" content="text/javascript">
+    <script type="text/javascript">
+      var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
+      function testInfo(phoneInput) {
+        var OK = re.exec(phoneInput.value);
+        if (!OK)
+          window.alert(phoneInput.value + ' isn\'t a phone number with area code!');
+        else
+          window.alert('Thanks, your phone number is ' + OK[0]);
+      }
+    </script>
+  </head>
+  <body>
+    <p>Enter your phone number (with area code) and then click "Check".
+        <br>The expected format is like ###-###-####.</p>
+    <form action="#">
+      <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
+    </form>
+  </body>
+</html>
+
+ +

{{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}

diff --git a/files/ar/web/javascript/guide/working_with_objects/index.html b/files/ar/web/javascript/guide/working_with_objects/index.html new file mode 100644 index 0000000000..83f3390467 --- /dev/null +++ b/files/ar/web/javascript/guide/working_with_objects/index.html @@ -0,0 +1,516 @@ +--- +title: العمل مع الكائنات +slug: Web/JavaScript/Guide/Working_with_Objects +translation_of: Web/JavaScript/Guide/Working_with_Objects +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
+ +

تم تصميم جافا سكريبت على نموذج بسيط يستند إلى الكائنات. الكائن هو عبارة عن مجموعة من الخصائص، كل خاصية لها اسم وقيمة key/value يمكن أن تكون قيمة هذه الخاصية عبارة عن دالة، وفي هذه الحالة يمكن ان تسمى بالوظيفة « method ». بالإضافة إلى الكائنات الأصلية التي توفرها بيئة المتصفحات، يمكنك انشاء كائنات خاصة بك. يصف هذا الفصل كيفية استخدام الكائنات، والخصائص والدوال او الوظائف، وايضا كيفية إنشاء الكائنات الخاصة بك.

+ +

نظرة عامة حول الكائنات

+ +
+

الكائنات في جافا سكريبت: كما هو الحال في العديد من لغات البرمجة الأخرى، يمكن مقارنة الكائنات بالحياة الحقيقية. ويمكن تشبيه مفهوم الكائنات في جافا سكريبت بالأشياء الملموسة في واقع الحياة.

+ +

في الجافاسكريبت، الكائن هو كيان مستقل بخصائصه وانواعه، يمكن مقارنته بكوب، على سبيل المثال.الكوب هو كائن له خصائصه، الكوب له لون، له شكل، له وزن، صنع بمواد معينة، واشياء اخرى. بنفس الطريقة، كائنات الجافا سكريبت لها ايضا خصائصها التي تميزها.

+ +

الكائنات والخصائص

+ +

كائنات الجافاسكريبت لها خصائص مرتبطة بها. يمكن تشبيه خاصية الكائن بمتغير مرتبط به. خصائص الكائن هي في الأساس نفس متغيرات جافا سكريبت العادية. خصائص الكائن تحدد مميزات الكائن، يمكنك الوصول إلى خصائص الكائن من خلال نقطة التدوين :

+ +
objectName.propertyName
+
+ +

ككل متغيرات جافاسكريبت،  اسم الكائن واسم الخاصية حساسة تجاه الاحرف (case sensitive). يمكنك تعيين خاصية ومنحها قيمة اولية. على سبيل المثال، لنقم بانشاء كائن باسم myCar وتعين خصائص له بالاسماء التالية : make, model و year كما في المثال التالي :

+ +
var myCar = new Object();
+myCar.make = 'Ford';
+myCar.model = 'Mustang';
+myCar.year = 1969;
+
+ +

خصائص الكائن الغير معرفة هي {{jsxref("undefined")}} (وليست {{jsxref("null")}}).

+ +
myCar.color; // undefined
+ +

يمكن الوصول الى خصائص الكائنات عن طريق الاقواس المربعة بدلا من نقطة التدوين، في بعض الاحيان يكون من الضروري استخدام الاقواس المربعة للوصول الى خصائص الكائن (لمزيد من المعلومات شاهد property accessors).  في بعض الاحيان تسمى الكائننات بمصفوفات مترابطة (associative arrays)، نظرا للشبه الكبير بينهما، حيث يمكن استخدام اسم الخاصية للوصول إلى قيمتها، الامر الذي تعتمده ايضا المصفوفات الترابطية. على سبيل المثال  يمكن الوصول إلى خصائص الكائن myCar على النحو التالي:

+ +
myCar['make'] = 'Ford';
+myCar['model'] = 'Mustang';
+myCar['year'] = 1969;
+
+ +

اسم خاصية الكائن يمكن ان يكون اي نوع من انواع النصوص الصحيحة لجافاسكريبت او اي شئ يمكن تحويله الى سلسلة نصية، بما في ذالك النص الفارغ، والنصوص التي تحتوي على رموز او اسماء محجوزة لجافاسكريبت والغير مسموح بها كمعرفات سواء بالنسبة لخصائص الكائن او للمتغيرات العادية على سبيل المثال، اسم خاصية يحتوي على مسافة او اسمين موصولين بواصلة (-) او الاسم الذي يبتدئ برقم. كل هذه الاشياء يمكن الوصول اليها عن طريق الاقواس المربعة فقط. هذه الاقواس فعالة جدا خصوصا مع اسماء الخصائص التي يتم تعينها بشكل ديناميكي (عندما لا يتم تحديد اسم الخاصية الا عند وقت التشغيل ). انظر الامثلة ادناه :

+ +
// four variables are created and assigned in a single go,
+// separated by commas
+var myObj = new Object(),
+    str = 'myString',
+    rand = Math.random(),
+    obj = new Object();
+
+myObj.type              = 'Dot syntax';
+myObj['date created']   = 'String with space';
+myObj[str]              = 'String value';
+myObj[rand]             = 'Random Number';
+myObj[obj]              = 'Object';
+myObj['']               = 'Even an empty string';
+
+console.log(myObj);
+
+ +

يرجى ملاحظة أن كافة المفاتيح في الاقواس المربعة تم تحويلها إلى سلسلة نصية (string type)، لان الكائنات في جافاسكريبت تتطلب بان يكون نوع المفتاح سلسلة نصية فقط، على سبيل المثال، في المثال اعلاه، عندما تم اضافة المفتاح rand الى ال myObj، الجافاسكريبت استدعت الوظيفة ()obj.toString بشكل اوتوماتيكي، واستخدمت ناتج السلسلة النصية كمفتاح جديد.  
+ مع العلم ان ("typeof rand === "number ).

+ +

يمكنك أيضا الوصول إلى الخصائص باستخدام قيمة نصية تم تخزينها في متغير :

+ +
var propertyName = 'make';
+myCar[propertyName] = 'Ford';
+
+propertyName = 'model';
+myCar[propertyName] = 'Mustang';
+
+ +

يمكنك استخدام for...in لعمل تكرار على خصائص الكائن القابلة للتصفح ( لمزيد من المعلومات حول enumerable properties ). لتوضيح ما نعنيه : تقوم الدالة التالية باظهار خصائص الكائن، عندما سيمرر لها الكائن واسم الكائن كبارامترات :

+ +
function showProps(obj, objName) {
+  var result = '';
+  for (var i in obj) {
+    // obj.hasOwnProperty() is used to filter out properties from the object's prototype chain
+    if (obj.hasOwnProperty(i)) {
+      result += objName + '.' + i + ' = ' + obj[i] + '\n';
+    }
+  }
+  return result;
+}
+
+ +

وهكذا، باستدعاء الدالة على هذا النحو showProps(myCar, "myCar") سينتج عنها النتائج التالية :

+ +
myCar.make = Ford
+myCar.model = Mustang
+myCar.year = 1969
+ +

تصفح خصائص الكائن

+ +

ابتداءا من ECMAScript 5، هناك ثلاثة طرق لتصفح/المرور على خصائص الكائن :

+ + + +

قبل ECMAScript 5، لم يكن هناك أية طريقة لتصفح كافة خصائص الكائن. الا انه، يمكن تحقيق ذلك باستخدام الدالة التالية:

+ +
function listAllProperties(o) {
+	var objectToInspect;
+	var result = [];
+
+	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) {
+      result = result.concat(Object.getOwnPropertyNames(objectToInspect));
+	}
+
+	return result;
+}
+
+ +

يمكن لهذه  الدالةان تكون مفيدة في الكشف عن الخصائص "المخفية" (الخصائص الموجودة في ال prototype chain والتي لا يمكن الوصول إليها من خلال الكائن، بسبب وجود خاصية اخرى لها نفس الاسم في ال prototype chain. لجدولة الخصائص الظاهرة فقط، عليك إزالة التكرار في المصفوفة.

+ +

إنشاء كائنات جديدة

+ +

جافا سكريبت لديها العديد من الكائنات المحددة مسبقاً. وبالإضافة إلى ذلك، يمكنك إنشاء كائنات خاصة بك. يمكنك إنشاء كائن باستخدام مهيئ الكائن (من المهم مراجعة هذا الموضوع حتي يمكنك فهم هذه الجزئية. كما انصح وبشدة مراجعة الفصل الخاص ب اساسيات الكائن في جافاسكريبت ).

+ +

كما يمكنك ايضا انشاء كائن بواسطة منشئ الوظيفة ( constructor function ) ومن ثم انشاء مثيل/نسخة له، من خلال الكلمة المحجوزة new.

+ +

استخدام object initializers

+ +

بالإضافة إلى إنشاء كائنات باستخدام constructor function، يمكنك إنشاء كائنات باستخدام مهيئ الكائن. هذا النوع من الكائنات  يشار إليه في بعض الأحيان ب object literal notation . وهو يتسق مع المصطلحات المستخدمة من قبل ++C.

+ +

التعبير عن كائن باستخدام object initializers:

+ +
var obj = { property_1:   value_1,   // property_# may be an identifier...
+            2:            value_2,   // or a number...
+            // ...,
+            'property n': value_n }; // or a string
+
+ +

حيث ان obj هو اسم الكائن الجديد، وكل property_i هو معرف الخاصية، يمكن ان يكون (اما اسما أو رقما أو سلسلة نصية)،في حين ان كل value_i هي تعليمة برمجية سيتم تعيينها كقيمه إلى الخاصية property_i يمكن (تعينها مباشرة او عن طريق اسنادها الى متغير خارجي).

+ +

تعريف ال obj هو اختياري، اذا لم تكن تريد الرجوع الى هذا الكائن فى اماكن اخرى، فلا حاجة لتعريفه إلى متغير. لاحظ انك ستحتاج الى احاطة object literal بين قوسين. حتى يعمل بشكل سليم. مثال:

+ +
var value_1 = 600,
+value_2 = 400;
+({
+    property_1: value_1,
+    2: value_2,
+    "property n": "Measurement",
+    init: function(){
+        console.log( this["property n"] +": "+ this.property_1 + "x" + this[2]);
+    }
+}).init(); // Measurement: 600x400
+
+
+ +

مهيئات الكائن، هي تعليمات برمجية، وكل مهئ سيخلق كائن جديد في التعليمة البرمجية التي سيتم تنفيذها. مهيآت الكائنات المتطابقة تنشئ كائنات مميزة والتي لا يمكن مقارنتها ببعضها البعض. يتم إنشاء الكائنات بنفس طريقة انشاء كائن جديد ()new Object، الكائنات المنشاة من خلال ال object literal هي مثيلات الكائن Object.

+ +

تقوم التعليمة البرمجية التالية، بانشاء كائن وتعيينه للمتغير x في حالة ما اذا كان الشرط صحيح:

+ +
if (cond) var x = {greeting: 'hi there'};
+
+ +

ينشئ المثال التالي، الكائن myHonda مع ثلاث خصائص. لاحظ أن الخاصية engine هي أيضا كائن له خصائصه.

+ +
var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
+
+ +

يمكنك أيضا استخدام مهيئات الكائن لإنشاء المصفوفات. شاهد array literals.

+ +

استخدام ال constructor function

+ +

كبديل، يمكنك إنشاء كائن مع هاتين الخطوتين:

+ +
    +
  1. تعريف نوع الكائن بانشاء constructor function. هناك عرف متفق عليه، وهو كتابة الحرف الاول من اسم الكائن بحروف كبيرة Capital.  بهدف تمييزه عن باقي الاسماء.
  2. +
  3. انشاء مثيل/نسخة للكائن بواسطة الكلمة المحجوزة new.
  4. +
+ +

لتحديد نوع الكائن، سنقوم بإنشاء دالة لتحديد اسم لهذا الكائن وخصائصه، ووظائفه، على سبيل المثال، فرضا انك تريد انشاء كائن للسيارات. سيتوجب عليك تسميته ب Car، وايضا يجب ان يمتلك خصائص مثل  make، model, و year.   للقيام بذلك، سيتوجب عليك انشاء الدالة التالية:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

لاحظ اننا استخدمنا this لتعيين قيم لخصائص الكائن استناداً إلى القيم التي سيتم تمريرها إلى بارامترات الدالة.

+ +

الآن يمكنك إنشاء كائن باسم mycar على النحو التالي:

+ +
var mycar = new Car('Eagle', 'Talon TSi', 1993);
+
+ +

تقوم هذه التعليمة البرمجية بانشاء mycar، واسناد القيم المحددة لخصائصه. وبالتالي قيمة  mycar.make هي قيمة نصية "Eagle"، و mycar.year قيمة رقمية 1993، وهلم جرا.

+ +

يمكنك إنشاء اي عدد من الكائنات من النوع Car واستدعاؤها عن طريق الكلمة المحجوزة new. مثال:

+ +
var kenscar = new Car('Nissan', '300ZX', 1992);
+var vpgscar = new Car('Mazda', 'Miata', 1990);
+
+ +

يمكن للكائن ان يحتوي على خاصية تكون هي نفسها كائن اخر، على سبيل المثال، فرضا انك تريد انشاء كائن تحت الاسم person كما يلي:

+ +
function Person(name, age, sex) {
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

ومن ثم إنشاء مثيلين/نسختين للكائن person كما يلي:

+ +
var rand = new Person('Rand McKinnon', 33, 'M');
+var ken = new Person('Ken Jones', 39, 'M');
+
+ +

ثم، يمكنك إعادة تعريف ال Car لتضمين الخاصية owner التي ستمتلك الكائن person كما يلي:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+
+ +

بعد ذلك يمكنك إنشاء مثيلات/نسخ للكائنات الجديدة، باستخدام ما يلي:

+ +
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
+var car2 = new Car('Nissan', '300ZX', 1992, ken);
+
+ +

لاحظ أنه بدلاً من تمرير سلسلة نصية أو قيمة رقمية عند إنشاء الكائنات الجديدة، في البيانات الواردة أعلاه تم تمرير الكائنان rand و ken كبرامترات خاصة بال owner. إذا كنت ترغب في معرفة الاسم الخاص ب car2، يمكنك الوصول إلى الخاصية بالطريقة التالية:

+ +
car2.owner.name
+
+ +

يمكنك  إضافة خاصية جديدة لكائن منشأ مسبقاً. على سبيل المثال، كما في التعليمة البرمجية التالية:

+ +
car1.color = 'black';
+
+ +

قمنا باضافة الخاصية color لل car1، وقمنا بتعيين القيمة "black." لها، ومع ذالك فهذا لن يجعلها متاحة لجميع الكائنات من النوع Car. لإضافة خاصية جديدة لكافة الكائنات من نفس النوع Car، يتوجب عليك اضافة هذه الخاصية لل constructor. الخاص بالكائن Car.

+ +

استخدام الوظيفة Object.create

+ +

يمكن أيضا إنشاء كائنات باستخدام الوظيفة {{jsxref("()Object.create")}} هذه الوظيفة يمكن أن تكون مفيدة للغاية، لأنها تتيح لك أن تختار ال prototype object للكائن الذي تريد إنشاء، دون الحاجة إلى تعريف ال constructor function (بواسطة new).

+ +
// Animal properties and method encapsulation
+var Animal = {
+  type: 'Invertebrates', // Default value of properties
+  displayType: function() {  // Method which will display type of Animal
+    console.log(this.type);
+  }
+};
+
+// Create new animal type called animal1
+var animal1 = Object.create(Animal);
+animal1.displayType(); // Output:Invertebrates
+
+// Create new animal type called Fishes
+var fish = Object.create(Animal);
+fish.type = 'Fishes';
+fish.displayType(); // Output:Fishes
+ +

الوراثة

+ +

في جافا سكريبت جميع الكائنات ترث من كائن واحد على الأقل. الكائن الذي ترث منه يسمى prototype، والخصائص الموروثة يمكن العثور عليها في ال prototype object لل constructor. شاهد Inheritance and the prototype chain  لمزيد من المعلومات.

+ +

فهرسة خصائص الكائن

+ +

يمكنك الاشارة/الوصول إلى خاصية الكائن إما عن طريق الاسم الخاص بها أو عن طريق المؤشر الترتيبي لها (index). إذا قمت في البداية بتعريف خاصية باسمها، سيتوجب عليك دائما الاشارة اليها باسمها، وكذالك اذا قمت في البداية بتعريف خاصية بمؤشرها الترتيبي، ايضا سيتوجب عليك الاشارة اليها بمؤشرها الترتيبي.

+ +

ينطبق هذا الشرط عند إنشاء الكائن وخصائصه داخل ال constructor (كما فعلنا سابقا مع  الكائن من النوع Car) وكذالك عند تحديد خصائص فردية بشكل واضح (على سبيل المثال، "myCar.color = "red). اذا قمت في البداية بتعريف خاصية بمؤشرها الترتيبي، مثل "myCar[5] = "25 mpg، وتريد بعد ذالك الوصول اليها سيتوجب عليك استخدام المؤشر الترتيبي على هذا النحو  myCar[5].

+ +

والاستثناء لهذه القاعدة هي كائنات ال HTML، مثل forms array. يمكنك الاشارة دائما إلى الكائنات في هذه المصفوفات إما عن طريق مؤشرهم الترتيبي (حسب وجودها في الوثيقة) او عن طريق اسمائها (إذا كانت معرفة). فمثلا، اذا كان الوسم الثاني <FORM> في الوثيقة له السمة (attribute ) باسم "myForm"، يمكنك الاشارة الى هذا الفورم ب document.forms[1] او ب document.forms["myForm"] او ب document.forms.myForm.

+ +

التحكم في خصائص الكائن

+ +

يمكنك إضافة خاصية إلى كائن محدد سابقا باستخدام الخاصية prototype. هذا النمط سيجعل هذه الخاصية متاحة لكافة الكائنات من النوع المحدد، بدلاً من تحديدها لمثيل واحد فقط. التعليمة البرمجية التالية تضيف الخاصية color الى جميع الكائنات من نوع Car، وبعد ذالك تقوم بتعيين القيمة الجديدة للخاصية color الخاصة بالكائن car1.

+ +
Car.prototype.color = null;
+car1.color = 'black';
+
+ +

شاهد  prototype property  لل Function object وايضا JavaScript reference لمزيد من المعلومات.

+ +

تعريف الوظائف

+ +

الوظيفة هي دالة مرتبطة مع الكائن، أو، ببساطة،  هي خاصية في الكائن قيمتها دالة، يتم تعريف الوظيفة بنفس الطريقة التي يتم بها تعريف الدالة العادية، باستثناء ان هذه الاخيرة يجب أن يتم تعيينها كخاصية لكائن. شاهد ايضا method definitions لمزيد من المعلومات، وكمثال على ما تم ذكره:

+ +
objectName.methodname = function_name;
+
+var myObj = {
+  myMethod: function(params) {
+    // ...do something
+  }
+
+  // OR THIS WORKS TOO
+
+  myOtherMethod(params) {
+    // ...do something else
+  }
+};
+
+ +

حيث ان ال objectName كائن موجود، وال methodname هو الاسم المعين إلى الوظيفة، و function_name هو اسم الدالة.

+ +

ثم يمكنك استدعاء الوظيفة في سياق الكائن كما يلي:

+ +
object.methodname(params);
+
+ +

يمكنك تعريف وظائف الكائن باستدعاء وظيفة معرفة في constructor الكائن. على سبيل المثال، يمكنك القيام بتعريف الدالة التي من شأنها تهيئة وعرض خصائص الكائن Car المعرف مسبقا، على سبيل المثال:

+ +
function displayCar() {
+  var result = 'A Beautiful ' + this.year + ' ' + this.make
+    + ' ' + this.model;
+  pretty_print(result);
+}
+
+ +

يمكنك استخدام الدالة pretty_print لاظهار الناتج على شكل نص افقي، تذكر ايضا على ان الكلمة المحجوزة this ستشير الى السياق الذي تنتمي اليه الدالة نفسها وفي هذه الحالة هو ال constructur Car

+ +

 يمكننا بعد ذالك تعيين هذه الدالة كوظيفة في ال constructeur Car على النحو التالي:

+ +
this.displayCar = displayCar;
+
+ +

التعليمة البرمجية النهائية:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+  this.displayCar = displayCar;
+}
+
+ +

الان يمكنك استدعاء الوظيفة displayCar لكلا الكائنين على النحو التالي:

+ +
car1.displayCar();
+car2.displayCar();
+
+ +

استخدام this كمرجع للكائنات

+ +

جافاسكريبت لديها الكلمة المحجوزة لها this، يمكنك استخدامها مع الوظائف للرجوع/الاشارة إلى الكائن الحالي. على سبيل المثال، لنفترض ان لديك دالة تسمى validate تقوم بالتحقق من صحة المدخلات:

+ +
function validate(obj, lowval, hival) {
+  if ((obj.value < lowval) || (obj.value > hival)) {
+    alert('Invalid Value!');
+  }
+}
+
+ +

يمكن استدعاء هذه الدالة  عن طريق معالج الحدث onchange، وستشير الكلمة المحجوزة this الى العنصر المتواجدة به (تنفيذ الدالة على هذا العنصر). كما في المثال التالي:

+ +
<input type="text" name="age" size="3"
+  onChange="validate(this, 18, 99)">
+
+ +

بشكل عام this تشير الى الكائن الذي يطلب الوظيفة.

+ +

يمكن ايضا استخدام this مع معالج الحدث بشكل مباشر، كما في المثال التالي:

+ +
<form name="myForm">
+<p><label>Form name:<input type="text" name="text1" value="Beluga"></label>
+<p><input name="button1" type="button" value="Show Form Name"
+     onclick="this.form.text1.value = this.form.name">
+</p>
+</form>
+ +

Defining getters and setters

+ +

 getter هي الوظيفة التي تقوم بجلب قيمة خاصية معينة. setter هي الوظيفة التي تقوم بتعيين قيمة لخاصية معينة. يمكنك تعيينها سواء للكائنات الاساسية المعرفة مسبقا أو الى الكائنات المعرف من قبل المستخدم والتي تدعم إضافة خصائص جديدة. وتستخدم مع ال object literal.

+ +

يبين المثال التالي كيفية انشاء getters و setters من طرف المستخدم :

+ +
var o = {
+  a: 7,
+  get b() {
+    return this.a + 1;
+  },
+  set c(x) {
+    this.a = x / 2;
+  }
+};
+
+console.log(o.a); // 7
+console.log(o.b); // 8
+o.c = 50;
+console.log(o.a); // 25
+
+ +

خصائص الكائن هي :

+ + + +

يمكنك استخدام  getters و setters مع الوظائف المنشاة مسبقا، لتحقيق ذالك يمكننا استخدام الوظيفة Object.defineProperty او الوظيفة القديمة Object.prototype.__defineGetter__

+ +

يبين الكود التالي كيف ان  getters و setters بامكانها ان ترث ال  {{jsxref("Date")}} prototype لاضافة الخاصية year الى جميع ال instances الخاص بالكائن Date المنشا مسبقا، ولهذا سنقوم باستخدام بعض الوظائف الخاصة ب Date ك getFullYear و setFullYear :

+ +
var d = Date.prototype;
+Object.defineProperty(d, 'year', {
+  get: function() { return this.getFullYear(); },
+  set: function(y) { this.setFullYear(y); }
+});
+
+ +

تبين التعليمة البرمجية التالية كيفية استخدام الخاصية year الجديدة التي تم انشاؤها عن طريق getters و setters:

+ +
var now = new Date();
+console.log(now.year); // 2000
+now.year = 2001; // 987617605170
+console.log(now);
+// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
+
+ +

بصفة عامة،  getters و setters يمكن ان تكون:

+ + + +

عندما سنقوم بانشاء getters و setters باستخدام ال استخدام object initializers كل ما عليك القيام به هو البذء بانشاء الوظيفة getter اولا ومن تم تعريفها ب get وتليها الوظيفة setter وتعريفها ب set، وبالطبع، الوظيفة getter لا تحتاج الى اي باراميتر، فيما ستحتاج الوظيفة setter لبراميتر واحد وهو القيمة الجديدة ل set. فعلى سبيل المثال:

+ +
var o = {
+  a: 7,
+  get b() { return this.a + 1; },
+  set c(x) { this.a = x / 2; }
+};
+
+ +

getters او setters. يمكن أيضا أن تضاف إلى كائن ما في أي وقت بعد انشائه باستخدام الوظيفة Object.defineProperties، البراميتر الأول لهذه الوظيفة هو الكائن الذي تريد انشاء ال getter او setter له. البراميتر الثاني عبارة عن كائن يمثل الخصائص التي ستضاف الى الكائن الهدف ويتكون من مفتاح الخاصية، وهو اسم ال  getter او ال setter، وقيمة الخاصية، وهي عبارة عن كائن لتعريف وظائف ال  getter او ال setter. لدينا هنا نفس المثال السابق يبين بجلاء ما تحدثنا عنه:

+ +
var o = { a: 0 };
+
+Object.defineProperties(o, {
+    'b': { get: function() { return this.a + 1; } },
+    'c': { set: function(x) { this.a = x / 2; } }
+});
+
+o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
+console.log(o.b); // Runs the getter, which yields a + 1 or 6
+
+ +

اي من هذه الاساليب هي الانسب ؟
+ إذا ذهبت بالفعل لمهيئ الكائن عند تعريف ال prototype فانت بحاجة الى الاسلوب الاول هذا الاسلوب محكم وبسيط. ومع ذالك، اذا كنت تنوي اضافة  getters و setters لاحقا بسبب انك لا تريد انشاء prototype او كائن معين سيكون افضل خيار هو الخيار الثاني. الخيار الثاني ربما يكون أفضل ويمثل الطابع الدينامي للجافا سكريبت، ولكن  يمكن ان يجعل الكود صعب القراءة والفهم.

+ +

حذف الخصائص

+ +

يمكنك حذف الخصائص الغير موروثة باستخدام الكلمة المحجوزة delete التعليمة البرمجية التالية توضح كيف يتم ذالك:

+ +
// Creates a new object, myobj, with two properties, a and b.
+var myobj = new Object;
+myobj.a = 5;
+myobj.b = 12;
+
+// Removes the a property, leaving myobj with only the b property.
+delete myobj.a;
+console.log ('a' in myobj); // yields "false"
+
+ +

يمكنك ايضا استخدام delete لحذف متغير عام، شرط ان لا يكون هذا المتغير معرف بواسطة الكلمة المحجوزة var.

+ +
g = 17;
+delete g;
+
+ +

مقارنة الكائنات

+ +

في جافا سكريبت، الكائنات تعمل كمرجع. لا يمكن المساوات بين كائنين مختلفين، حتى وان كان لديهما نفس القيم لنفس الخصائص. سيكون هناك تكافؤ فقط إذا تم مقارنة كائن بحد ذاته.

+ +
// Two variables, two distinct objects with the same properties
+var fruit = {name: 'apple'};
+var fruitbear = {name: 'apple'};
+
+fruit == fruitbear; // return false
+fruit === fruitbear; // return false
+ +
// Two variables, a single object
+var fruit = {name: 'apple'};
+var fruitbear = fruit;  // assign fruit object reference to fruitbear
+
+// here fruit and fruitbear are pointing to same object
+fruit == fruitbear; // return true
+fruit === fruitbear; // return true
+
+ +
fruit.name = 'grape';
+console.log(fruitbear);    // yields { name: "grape" } instead of { name: "apple" }
+
+ +

لمزيد من المعلومات حول عوامل المقارنة، شاهد Comparison operators.

+
+ +

See also

+ + + +

{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}

diff --git "a/files/ar/web/javascript/guide/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" "b/files/ar/web/javascript/guide/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" new file mode 100644 index 0000000000..af934b397d --- /dev/null +++ "b/files/ar/web/javascript/guide/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" @@ -0,0 +1,698 @@ +--- +title: الدوال +slug: Web/JavaScript/Guide/الدوال +tags: + - الدوال + - جافا سكريبت + - دليل +translation_of: Web/JavaScript/Guide/Functions +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}
+ +

الدوال هي واحدة من اللبنات الأساسية في جافاسكريبت. الدالة، هي عبارة عن مجموعة من التعليمات البرمجية التي تؤدي وظيفة معينة. حتى تتمكن من إستخدام الدالة، عليك أولا تعريفها في مكان ما من النطاق الذي تود إستدعائها منه.

+ +
+

يمكنك القاء نظرة في مرجع مفصل عن دوال الجافاسكريبت حتى تتعرف على تفاصيل اكثر.

+ +

انشاء الدوال

+ +

الاعلان عن الدوال - الصيغة الافتراضية - Function declarations

+ +

تعريف الدالة: تتكون الدالة من الكلمة المحجوزة function، متبوعة بـ :

+ + + +

على سبيل المثال، الكود التالي يعرف دالة بسيطة تسمى square :

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

الدالة square تمتلك بارامتر واحد، هو number. وتعليمة برمجية واحدة تقوم بإرجاع بارامتر الدالة number مضروباً في نفسه. والتعليمة return تحدد القيمة التي سترجعها الدالة.

+ +
return number * number;
+
+ +

يتم تمرير البارامترات الاولية primitives (كالسلاسل الحرفية، الاعداد...الخ) الى الدالة، بوسيلة تسمى، الاستدعاء بالقيمة، call by value وهي، ان يتم تحليل argument الدالة، والقيمة الناتجة سَتُرسل نسخة منها فقط إلى المتغير المستقبل (بارامتر الدالة)، بعد ذالك تقوم الدالة بتخزين هذه القيمة في الذاكرة، ثم، إذا كانت الدالة قادرة على تعيين القيم للبارامترات الخاصة بها، تبدا بالعمل على هذه النسخة فقط، دون تغيير اي شئ في قيمة المتغير الاصلي.

+ +

في المثال التالي، لدينا المتغير value سنقوم بتمريره إلى الدالة square. ثم ضمن الدالة square سيتم إنشاء نسخة جديدة، وهكذا، حتى وان قمنا بتغيير القيمة داخل الدالة، فلن يؤثر هذا على قيمة المتغير الأصلي الذي تم تعريفه خارج الدالة. لان هذا التغيير لن يكون مرئيا خارج الدالة:

+ +
function square(number) { // parameter = recipient
+  return number * number;
+}
+var value = 10;
+square(value);   // argument = Sender
+document.write(value);  // log: 10
+
+ +

على عكس المثال السابق، اذا قمت بتمرير كائن (مثلا، قيمة غير اولية ك {{jsxref("Array")}} او كائن معرف من قبل المستخدم) كبارامتر، وقامت الدالة بتغيير خصائص الكائن، سيكون هذا التغيير مرئيا خارج الدالة:

+ +
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

+ +

في حين ان الدالة اعلاه تم الاعلان عنها بصيغة  function declaration، يمكن ايضا انشاء الدوال بصيغة ال function expression. كما يمكن ايضا للدوال ان تكون بصيغة ال anonymous (دوال مجهولة الاسم). على سبيل المثال، الدالة square يمكن تعريفها ايضا بصيغة ال function expression على النحو التالى:

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

يمكن تعيين اسم للدوال بصيغة ال function expression، لجعل الدالة تعيد استدعاء ذاتها (الاستدعاء الداتي)، أو استخدامه في المنقح debugger. او لتعقب اخطاء الدالة من خلال stack traces.

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

يمكنك تمرير دالة كبارامتر لدالة اخرى. يظهر المثال التالي الدالة map تستخدم دالة اخرى كبارامتر اول لها :

+ +
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;
+}
+
+ +

طريقة استخدامها مع الصيغة function expression:

+ +
var multiply = function(x) { return x * x * x; };
+map(multiply, [0, 1, 2, 5, 10]);
+
+ +

طريقة استخدامها مع الصيغة anonymous function مباشرة:

+ +
map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]);
+
+ +

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

+ +

في الجافاسكريبت يمكن الاعلان عن دالة اعتمادا على شرط. على سبيل المثال، ستقوم التعليمة البرمجية التالية بالاعلان عن الدالة myFunc شرط ان يكون  num يساوي 0:

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

بالإضافة إلى انشاء الدوال كما هو موضح اعلاه، يمكنك ايضا استخدام الصيغة {{jsxref("Function")}} constructor لانشاء دوال من خلال السلاسل النصية، تنفذ وقت التشغيل، تماما كما في  {{jsxref("eval", "()eval")}}.

+ +

هناك فرق بين الدوال (functions) والوظائف (methods)، الدوال هي ما نناقشه في هذا الفصل، والوظائف هي تلك المرتبطة بالكائنات (قيمة لخاصية في الكائن)، اقرأ المزيد حول الكائنات والوظائف العمل مع الكائنات [عربي].

+ +

إستدعاء الدوال

+ +

تعريف الدالة يعني ببساطة إعطاء إسم لها وتحديد ماستقوم به عندما يتم إستدعائها. أما إستدعاء الدالة فيقوم فعليا بتنفيذ الإجراءات مع البرامترات المحددة. على سبيل المثال، إذا قمت بتعريف الدالة square، فستقوم بإستدعائها كما يلي :

+ +
square(5);
+
+ +

تقوم التعليمة البرمجية اعلاه باستدعاء الدالة مع البارامتر 5. ثم تقوم بتنفيذ التعليمات البرمجية المرتبطة بها وترجع القيمة 25.

+ +

الدوال يجب ان تنتمي للنطاق الذي استدعيت فيه، ولان الدوال بصيغة function declaration ترفع اعلى النطاق، فمن الممكن أن تعرف في وقت لاحق، كما في المثال التالي:

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

نطاق الدالة هو اما الدالة التي تم الإعلان عنها، أو البرنامج بأكمله إذا تم الاعلان عنها في المستوى العلوي.

+ +
+

ملاحظة: سيعمل هذا فقط عندما يتم تعريف الدالة باستخدام الصيغة (مثل {}()function funcName). اما التعليمة البرمجية التالية فسوف لن تعمل، وهذا يعني ان الية الرفع (hoisting) بالنسبة للدوال تعمل فقط مع الدوال ذات الصيغة function declaration ولا تعمل مع الدوال ذات الصيغة 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;
+}
+
+ +

arguments الدالة لا تقتصر على الاعداد او السلاسل الحرفية فقط، يمكنك تمرير الكائنات ايضا. في القسم الخاص بالعمل مع الكائنات العمل مع الكائنات[عربي] توجد دالة باسم ()showProps توضح كيفية تمرير كائن ك argument للدالة.

+ +

يمكن للدالة أن تقوم بإستدعاء ذاتها. على سبيل المثال، هذه الدالة تقوم بحساب المضروب بشكل متكرر :

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

في كل مرة تقوم الدالة باستدعاء ذاتها، يتم خصم 1 من قيمة البرامتر الممرر، ويتم ضرب القيمة المحصلة في القيمة العائدة من جديد، فرضا، اذا كانت القيمة الممررة 5، الاستدعاء الاول سيكون 5، الاستدعاء الثاني سيكون 4، الاستدعاء الثالث سيكون 3، وهكذا، ويتم ضرب هذه القيم العائدة مع بعضها البعض. بهذا الشكل :  5 * 4 * 3 * 2 * 1 == 120

+ +

امثلة متنوعة:

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

هناك طرق أخرى لاستدعاء الدوال. غالبا ما تكون هناك حالات تحتاج الى دالة تُستدعى بشكل ديناميكي، حيث يمكن التعامل مع مجموعة من ال arguments، وحيث سياق (context) استدعاء الدالة يجب ان ينشا في وظيفة لكائن يحدد وقت التشغيل. وهذا يبين ان الدوال هي نفسها كائنات، وهذه الكائنات بدورها لديها وظائف ( شاهد {{jsxref("Function")}} object). من ضمن هذه الوظائف، الوظيفة {{jsxref("Function.apply", "()apply")}} يمكن استخدامها لتحقيق هذه الاهداف.

+ +

نطاق الدالة

+ +

المتغيرات المعرفة داخل الدالة لايمكن الوصول إليها من أي مكان آخر خارج الدالة، لأن هذه المتغيرات معرفة فقط داخل نطاق الدالة. على كل، يمكن للدالة الوصول إلى كل المتغيرات والدوال المعرفة في النطاق المعرفة فيه الدالة. بعبارة أخرى، الدالة المعرفة في النطاق العام تستطيع الوصول إلى كل المتغيرات المعرفة في النطاق العام. الدالة المعرفة داخل دالة أخرى يمكنها أيضا الوصول إلى كل المتغيرات المعرفة في دالتها الأم وكل المتغيرات الأخرى التي يمكن للدالة الأم الوصول لها.

+ +
// المتغيرات التالية معرفة في النطاق العام
+var num1 = 20,
+    num2 = 3,
+    name = "Chamahk";
+
+// هذه الدالة معرفة في النطاق العام
+function multiply() {
+  return num1 * num2;
+}
+
+multiply(); // Returns 60
+
+// مثال على دالة داخل دالة
+function getScore () {
+  var num1 = 2,
+      num2 = 3;
+
+  function add() {
+    return name + " scored " + (num1 + num2);
+  }
+
+  return add();
+}
+
+getScore(); // Returns "Chamahk scored 5"
+
+ +

النطاق ومكدس الدوال

+ +

الاستدعاء الذاتي

+ +

يمكن للدالة ان تستدعي داتها بثلاثة طرق:

+ +
    +
  1. من خلال اسم الدالة
  2. +
  3. arguments.callee
  4. +
  5. من خلال المتغيرات التي تشير إلى الدالة
  6. +
+ +

على سبيل المثال، انظر الدالة التالية:

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

تضمين الاستدعاء الذاتي داخل جسم الدالة bar:

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

الدوال التي تقوم باستدعاء نفسها تسمى recursive function. الاستدعاء الداتي يشبه آلِية الحلقات في بعض النواحي، كلاهما ينفذان التعليمات البرمجية نفسها عدة مرات، وايضا كلاهما يتطلبان تعبيرا شرطيا (لتجنب التكرار الى ما لا نهاية، او بالاحرى، الاستدعاء الذاتي الى ما لا نهاية في حالتنا هذه). على سبيل المثال، الحلقة التالية:

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

المثال التالي يبين دالة تقوم بالاستدعاء الذاتي، يمكنها محاكات الحلقة :

+ +
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);
+
+ +

ومع ذلك، لا يمكن أن تكون بعض الخوارزميات حلقات تكرارية بسيطة. على سبيل المثال، الوصول الى كافة العقد nodes في بنية الشجرة DOM سيكون اسهل واكثر تفصيلا باستخدام الاستدعاء الذاتي:

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

على عكس الحلقات التكرارية البسيطة، والتي تقوم بالتكرار السطحي على DOM، تمكننا دوال الاستدعاء الداتي من تنفيذ عدة استدعاءات، كل استدعاء داتي ينتج عنه العديد من الاستدعاءات الفرعية، بمعنى ان هذا النوع من الدوال يمكنها الوصول الى عمق ال DOM. لتتيح لك امكانية التعامل مع كل جزئية فيه. كما يوضح المثال التالي:

+ +
var walkTree = function recycle( node, fn ) {
+	fn( node );
+	node = node .firstChild;
+	while( node ){
+		recycle( node, fn );
+		node = node.nextSibling;
+	}
+}
+
+walkTree( document.body , function( node ){
+	if( node.nodeType == 1 ){
+		// do something with [object HTMLElements]
+	}
+	if( node.nodeType == 3 ){
+		// do something with [object Text]
+	}
+});
+
+ +

كلا الدالتين اعلاه، تؤدي نفس الغرض، لا اختلاف بينهما، الفرق الوحيد هو شكل بناء الدالة، حيث بنيت الدالة الاولى على طريقة ال  function declaration  فيما بنيت الدالة الثانية على شكل، ال  function expression  وال  anonymous function، وكلاهما تنتهج اسلوب recursive function.

+ +

من الناحية النظرية، من الممكن تحويل أي خوارزمية الاستدعاء الذاتي الى خوارزمية الاستدعاء العادي (مع الحلقات، على سبيل المثال). عموما، المنطق الناتج أكثر تعقيداً ويتطلب استخدام  المكدس. الاستدعاء الذاتي أيضا يستخدم المكدس، مكدس الدالة function stack.

+ +

سلوك مكدس الذاكرة المؤقتة يمكن أن ينظر إليه كما في المثال التالي:

+ +
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
+ +

الدوال المتداخلة  و الاغلاق (closures)

+ +

يمكن انشاء دالة داخل دالة اخرى. الدالة الداخلية هي دالة خاصة private بالدالة الخارجة. الدالة الداخلية تشكل الاغلاق closure، والإغلاق هو فقط تعبير (عموما الاغلاق هو دالة). والذي يمكنه الوصول إلى المتغيرات المجانية free variables (المصطلح free variable يشير الى المتغيرات المستخدمة في الدالة، وهي ليست متغيرات محلية او بارامترات لهذه الدالة. بمعنى اخر هي متغيرات معرفة خارج الدالة وتستفيد منها الدالة، وهذا هو سبب تسميتها بالمتغيرات المجانية)،  كما يمكنه ايضا، الوصول الى اي شئ في البيئة التي ترتبط بها هذه المتغيرات المجانية.

+ +

بما ان الدالة الداخلية هي closure. فهذا يعني انها تستطيع ان ترث البرامترات والمتغيرات من الدالة الخارجية. بمعنى اخر، الدالة الداخلية تمتلك النطاق الخاص بالدالة الخارجية.

+ +

الخلاصة:

+ + + +

يظهر المثال التالي الدوال المتداخلة:

+ +
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
+
+ +

بما ان الدالة الداخلية تشكل closure. فمن الضروري استدعاء الدالة الخارجية أولا، بعد ذالك يمكنك تحديد ال  arguments لكل منهما :

+ +
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
+
+ +

الحفاظ على المتغيرات

+ +

في المثال اعلاه، لاحظ كيف تم الحفاظ على x عندما تم ارجاع الدالة inside. الاغلاق يحفاظ على البرامترات والمتغيرات في جميع النطاقات التي تشير إليه. مع كل استدعاء للدالة الخارجية، يمكنك تعيين arguments مختلفة، سيتم إنشاء إغلاق جديد مع كل استدعاء للدالة outside. يمكن تحرير الذاكرة فقط عندما يكون عائد الدلة inside غير متاحا.

+ +

وهذا لا يختلف عن تخزين المراجع في كائنات أخرى، ولكن غالبا ما يكون أقل وضوحاً نظراً لعدم تعيين المراجع مباشرة ولا يمكن فحصها.

+ +

الدوال الاكثر تداخلا

+ +

الدوال يمكن ان تكون اكثر تداخلا، بمعنى، الدالة (A) تحتضن الدالة (B)، والدالة (B) تحتضن الدالة (C). هنا كل من الدالة B و C تشكل closures، وهكذا B يمكنها الوصول الى  A، و  C يمكنها الوصول الى B. بالاضافة الى ذالك، C يمكنها الوصول الى B و A، وبالتالي، الإغلاق يمكن أن يحتوي على عدة نطاقات. وهذا ما يسمى بسلسلة النطاق scope chaining. (سيتم شرح لماذا يطلق عليه "تسلسل" في وقت لاحق).

+ +

انظر في المثال التالي:

+ +
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)
+
+ +

في هذا المثال C تصل الى y الخاصة ب B وايضا الى x الخاصة ب A، أصبح هذا ممكناً لأن:

+ +
    +
  1. B تشكل closure، وتمتلك A، بمعنى B يمكنها الوصول الى البارامترات والمتغيرات الخاصة ب A.
  2. +
  3. C تشكل closure، وتمتلك B.
  4. +
  5. بسبب ان B تمتلك A، فقد اصبح C يمتلك A، وعليه ف C يمكنه الوصول الى البارامترات والمتغيرات الخاصة ب B و A. بعبارات أخرى، C سلسلة نطاقات ل B و A في هذا الترتيب.
  6. +
+ +

العكس ليس صحيحاً. A لا يمكنها الوصول الى C، لان A لا يمكنها الوصول لاي من البارامترات او المتغيرات الخاصة ب B. (فيما C هي متغير لها). وهكذا، C ستصبح خاصة private فقط ب B.

+ +

تضارب الاسماء

+ +

عند وجود اثنين من البارامترات أو المتغيرات التي تحمل نفس الاسم في نطاقات الاغلاق، فهذا يسمى تضارب في الاسماء، وفي هذه الحالة، ستكون الاسبقية للنطاقات الاكثر عمقا في استخدام هذا الاسم، اما بالنسبة للنطاقات الأكثر سطحية سوف تحظى بأولوية أدنى لاستخدام هذا الاسم، من وجهة نظر سلسلة النطاق، النطاق الاول في السلسلة هو النطاق الاكثر عمقا ( اسفل السلسلة)، والنطاق الاخير في السلسلة هو النطاق الاكثر سطحية (اعلى السلسلة). شاهد المثال التالي:

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

يحدث تعارض الاسم  في التعليمة return x، وهو مابين الباراميتر x الخاص ب inside وبين المتغير x الخاص ب outside. سلسلة النطاق سترى الامر على هذا النحو {inside, outside, global object}. وبناءا عليه x الخاص ب inside سياخد الاسبقية على x الخاص ب outside، وبالتالي الناتج هو 20 (inside x) بدلا من 10 (outside x).

+ +

الاغلاقات - Closures

+ +

الإغلاق هي واحدة من أقوى المميزات في جافا سكريبت. جافا سكريبت تسمح بتداخل الوظائف وتمنح الدوال الداخلية حق الوصول الكامل إلى كافة المتغيرات والدوال المعرفة داخل الدالة الخارجية (وجميع المتغيرات والدوال الأخرى التي يمكن للدالة الخارجية الوصول إليها). ومع ذالك، الدوال الخارجية لا يمكنها الوصول الى المتغيرات والدوال المعرفة داخل الدوال الداخلية. وهذا يوفر نوعا من الحماية للمتغيرات والدوال الداخلية. وأيضا، لأن الدوال الداخلية لديها حق الوصول إلى نطاق الدالة الخارجية، فالمتغيرات والدوال المعرفة داخل الدالة الخارجية ستدوم اطول من مدة تنفيذ الدالة الخارجىة، اذا تمكنت الدالة الداخلية ان تدوم أطول من الدالة الخارجية. يتم إنشاء الاغلاق عندما تكون الدالة الداخلية بطريقة أو بأخرى في متناول أي نطاق خارج الدالة الخارجية.

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

من الناحية العملية، يمكن أن تكون المسالة أكثر تعقيداً من التعليمات البرمجية أعلاه. يمكن إرجاع كائن والذي سيحتوي على وظائف للتعامل مع المتغيرات الداخلية للدالة الخارجية:

+ +
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
+
+ +

في التعليمات البرمجية اعلاه، المتغير 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
+
+ +

ومع ذلك، يجب الاحتراس جيدا من الوقوع في بعض الفخاخ عند استخدام عمليات الإغلاق. إذا كانت دالة مغلقة تعرف متغير بنفس الاسم، كاسم متغير في النطاق الخارجي، فلا توجد طريقة للإشارة إلى المتغير في النطاق الخارجي مرة أخرى.

+ +
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 ???
+    }
+  }
+}
+
+ +

الكلمة المحجوزة this (في بعض الاحيان تسمى بالمتغير العجيب)، ينبغي التعامل معها بحذر في حالات الإغلاق. احذر، ف this تشير إلى السياق حيث سيتم استدعاء الدالة وليس إلى المكان حيث تم تعريف الدالة.

+ +

استخدام الكائن arguments

+ +

يمكنك التعامل مع  arguments الدالة من الداخل، من خلال الكائن (arguments او الحجج). يمكنك معالجة ال  arguments الممررة الى الدالة على النحو التالي:

+ +
arguments[i]
+
+ +

حيث ان i هو الفهرس الرقمي لل arguments، ويبتدئ من 0، وبالتالي، ال argument الاول الممرر الى الدالة سيكون arguments[0]. لمعرفة عدد ال arguments الممررة نستخدم arguments.length.

+ +

باستخدام الكائن arguments، يمكنك استدعاء دالة مع arguments أكثر من التي تم التصريح بها رسميا. وهي مفيذة جدا، خصوصا إذا كنت لا تعرف مسبقاً كم عدد ال  arguments التي ستمرر اثناء استدعاء الدالة. يمكنك استخدام arguments.length لمعرفة عدد البرامترات الممرة الى الدالة، حتى تتمكن بعد ذالك من التعامل معها من خلال الكائن arguments.

+ +

على سبيل المثال، يمكننا انشاء دالة تقوم بوصل عدة سلاسل حرفية. ال argument الوحيد المحدد رسميا في الدالة، هو السلسلة الحرفية التي ستفصل بين باقي السلاسل الحرفية التي ستمرر ك arguments بعد ال argument الرسمي للدالة.  كما في المثال التالي:

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

يمكنك تمرير اي عدد من ال arguments لهذه الدالة، وسترتبط ببعضها البعض من خلال ما سيمرر الى ال argument الرسمي:

+ +
// 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");
+
+ +
+

ملاحظة: المتغير arguments هو شبه مصفوفة، ولكنه ليس مصفوفة. وانما يتصرف كالمصفوفة، يستخدم الفهرسة الرقمية، يستخدم الخاصية length، ومع ذالك، لا يمكنه استخدام الوظائف الخاصة بالمصفوفات مثل push او join ...الخ.

+
+ +

الفرق بين parameters و arguments

+ +

Function parameters او بارامترات الدالة، هي الأسماء المدرجة في تعريف الدالة. فيما Function arguments هي القيم الحقيقية التي تمرر إلى الدالة عند الاستدعاء (راجع التعريف والاستدعاء اعلى الصفحة). انظر المثال التالي:

+ +
function foo( param1, param2, ...) // parameters {
+    // Do things
+}
+foo(arg1, arg2, ...); // arguments
+
+ +
+

ملاحظة: ال parameter هو متغير باسم معين يمرر الى الدالة. تستخدم الباراميترات لجلب ال arguments داخل الدوال.

+
+ +

راجع الكائن {{jsxref("Function")}} في مرجع الجافا سكريبت لمزيد من المعلومات.

+ +

بارامترات الدالة

+ +

بدأً من ECMAScript 6، أصبح هناك نوعان من البارامترات: البارامترات الإفتراضية وبقية البارامترات.

+ +

البارامترات الإفتراضية

+ +

في الجافاسكريبت، القيمة الافتراضية لبرامترات الدوال هي undefined. ومع ذالك، في بعض الحالات، قد يكون من المفيد تعيين قيمة افتراضية مختلفة. البارامترات الافتراضية يمكنها تدارك الموقف.

+ +

قبل ECMAScript 2015، كانت الاستراتيجية العامة لوضع الافتراضات هي اختبار قيمة البارامتر في جسم الدالة وتعيين قيمة له اذا كانت قيمته undefined. على سبيل المثال، في التعليمة البرمجية التالية، لم يتم تحديد قيمة للبارامتر b في الاستدعاء، وبالتالي قيمتة ستساوي undefined، عند اختبار (a * b) ستعود الدالة multiply ب NaN. لتجنب هذا،  يقوم السطر الثاني في التعليمة البرمجية اسفله بتعيين قيمة افتراضية للبارامتر b:

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

ابتداءا من ECMAScript 2015، اصبح من الممكن عمل اعدادات افتراضية على غرار (php)، والاختبار في جسم الدالة لم يعد ضروريا. الان، ببساطة يمكنك تعيين 1 كقيمة افتراضية للبارامتر b في تعريف الدالة:

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

لمزيد من التفاصيل، راجع  default parameters في مرجع الجافاسكريبت.

+ +

بقية البارامترات - rest parameter

+ +

الصيغة rest parameter تسمح بتمثيل عدد غير محدود من ال arguments كمصفوفة. في هذا المثال، نستخدم بقية البارامترات لتجميع ال arguments ابتداءا من البرامتر الثاني لغاية النهاية. ثم نقوم بضربها باول بارامتر. هذا المثال يستخدم دالة السهم، والتي سندرسها في القسم التالي.

+ +
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

+ +

تعبيرات دوال السهم تسمح لك باستخدام تعبيرا أكثر إيجازاً من التعبير عن الوظائف الكلاسيكية. والقيمة this يتم ربطها بشكل نحوي. فيما تكون دوال السهم مجهولة الاسم anonymous. راجع ايضا هذه المدونة  ES6 In Depth: Arrow functions.

+ +

اثنين من العوامل التي أثرت في مقدمة دوال السهم: الدوال المختصرة و lexical this.

+ +

الدوال المختصرة

+ +

في بعض الأنماط الوظيفية، الدوال المختصرة هي موضع ترحيب. قارن التعليمات البرمجية التالية:

+ +
var a = [
+  "Hydrogen",
+  "Helium",
+  "Lithium",
+  "Beryl­lium"
+];
+
+var a2 = a.map(function(s){ return s.length });
+
+var a3 = a.map( s => s.length );
+ +

التعليمة Lexical this

+ +

قبل وجود وظائف السهم، كانت كل دالة جديدة تعرف قيمة ال this الخاصة بها (كائن جديد في حالة الدالة الإنشائية، undefined في استدعاءات الدوال مع الوضع الصارم، في سياق الكائن قيد التشغيل في حالة الوظيفة، إلخ.). وهذا يمكن أن يسبب بعض المشاكل مع نمط البرمجة الكائنية:

+ +
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();
+ +

في ECMAScript 3/5، تم إصلاح هذه المشكلة عن طريق تخزير القيمة this في متغير اخر.

+ +
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);
+}
+ +

بدلا من ذلك، يمكننا إنشاء دالة ملزمة bound function بحيث تكون "احسن"  قيمة this سيتم تمريرها إلى الدالة ()growUp.

+ +

دوال السهم تلتقط القيمة this من السياق المغلق (enclosing context)، لذا ستعمل التعليمة البرمجية التالية كما هو متوقع.

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

دوال معرفة مسبقا

+ +

جافا سكريبت لديها العديد من الوظائف المدمجة ذات المستوى الاعلى top-level :

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

الوظيفة ()eval تستخدم لاختبار شفرة الجافا سكريبت على شكل سلسلة حرفية.

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

الوظيفة ()uneval تستخدم لانشاء سلسلة حرفية عبارة عن مصدر كود الكائن {{jsxref("Object")}}.

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

الدالة العامة () isFinite تقوم بتحديد ما إذا كانت القيمة التي تم تمريرها عدد محدود. إذا لزم الأمر، يتم تحويل البارامتر إلى رقم.

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

تستخدم الدالة()isNaN للتاكد من ان القيمة ليست رقمية {{jsxref("Global_Objects/NaN", "NaN")}}  ملاحظة: يمكننا ايضا استخدام {{jsxref("Number.isNaN()")}}, الجديدة في ECMAScript 6 او استخدام التعليمة typeof. كلها تادي نفس الغرض.

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

تستخدم الدالة ()parseFloat لتحويل سلسلة حرفية الى عدد كسري.

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

تستخدم الدالة ()parseInt لتحويل سلسلة حرفية الى عدد صحيح (البارامتر الثاني خاص بالتعامل مع القاعدة في الأنظمة العددية الرياضية).

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

تستخدم الدالة ()decodeURI لفك تشفير معرف الموارد الموحد (Uniform Resource Identifier (URI التي تم إنشاؤها مسبقا من طرف {{jsxref("Global_Objects/encodeURI", "encodeURI")}} او عن طريق نفس الروتين.

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

تستخدم الوظيفة ()decodeURIComponent لفك تشفير معرف عناصر الموارد الموحدة (Uniform Resource Identifier (URI التي تم إنشاؤها مسبقا من طرف {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} او عن طريق نفس الروتين.

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

تستخدم الوظيفة ()encodeURI لتشفير معرف الموارد الموحد (Uniform Resource Identifier (URI باستبدال كل مثيل من أحرف معينة بواحد، اثنان، ثلاثة، أو أربعة تهريبات متوالية تمثل ترميز الاحرف UTF-8 (لن يكون إلا أربع تهريبات متوالية لرموز تتألف من اثنين من الحروف "البديلة").

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

تستخدم الوظيفة ()encodeURIComponent لتشفير معرف عناصر الموارد الموحدة (Uniform Resource Identifier (URI باستبدال كل مثيل من أحرف معينة بواحد، اثنان، ثلاثة، أو أربعة تهريبات متوالية تمثل ترميز الاحرف UTF-8 (لن يكون إلا أربع تهريبات متوالية لاحرف تتألف من اثنين من الحروف "البديلة").

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

الوظيفة ()escape الغير مرغوب فيها. تحتسب سلسلة جديدة من بعض الأحرف التي يجب استبدلها من قبل hexadecimal escape sequence. استخدم {{jsxref("Global_Objects/encodeURI", "encodeURI")}} او استخدم {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} بدلا عنها.

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

الوظيفة()unescape الغير مرغوب فيها. تحتسب سلسلة جديدة بحيث hexadecimal escape sequence. اسبدلت مع الرمز الذي يمثلها. متتالية التهريب يمكن ان تاتى من دالة مثل {{jsxref("Global_Objects/escape", "escape")}}. على العموم استخدم {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} او استخدم {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} بدلا عنها.

+
+
+ +

 

+
+ +

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

diff --git a/files/ar/web/javascript/index.html b/files/ar/web/javascript/index.html new file mode 100644 index 0000000000..9c99dab71c --- /dev/null +++ b/files/ar/web/javascript/index.html @@ -0,0 +1,121 @@ +--- +title: جافاسكربت +slug: Web/JavaScript +tags: + - جافاسكربت + - صفحة هبوط +translation_of: Web/JavaScript +--- +

{{JsSidebar}}

+ +

جافاسكربت (JavaScript®) (إختصاراً JS) هي لغة برمجة خفيفة، مُفسرة، وشيئيّة ذات دوال من الدرجة الأولى، وهي مشهورة خصوصاً بكونها لغة البرمجة النصيّة لصفحات الويب، لكنها تستعمل في بيئات أخرى غير المتصفحات مثل node.js أو Apache CouchDB. فهي لغة برمجة نصيّة ديناميكيّة مبنية على النماذج و متعددة النماذج، وهي تدعم نمطي البرمجة الحتمي (imperative) الوظيفي (functional). اقرأ المزيد عن جافا سكربت.

+ +

يختص هذا الجزء بالجافاسكربت كلغة برمجة، بغض النظر عن مواقع الويب أو البيئات التي يمكن لهاته اللغة أن تعمل عليها.  للمزيد من المعلومات حول الواجهات البرمجيّة الخاصة بمواقع الويب،  طالع DOM و الواجهات البرمجيّة للويب.

+ +

يسمى معيار الجافا سكربت ECMAScript. بدءً من عام 2012، جميع المتصفحات الحديثة تدعم بشكل كامل ECMAScript 5.1. المتصفحات القديمة تدعم على الأقل ECMAScript 3. في 17 يونيو 2015، تم نشر النسخة الرئيسيّة السادسة من ECMAScript. ويسمى هذا الإصدار رسمياً ECMAScript 2015، ولكن يشار إليه عادةً باسم ECMAScript 6 أو ES6. تشير هذه الوثائق إلى الإصدار الأحدث من اللغة، والذي هو ECMAScript 2018.

+ +

لا ينبغي الخلط بين الجافاسكربت ولغة البرمجة جافا. يعد كلاً من الأسمين "جافا" و "جافاسكربت" علامات تجاريّة مُسجلة لشركة أوراكل في الولايات المتحدة الأمريكيّة وغيرها من البلدان. كلتا اللغتين تملكان بنيّة كتابيّة مختلفة، ودلالة مختلفة، وكذلك استخدامات مختلفة.

+ +
+
+

دورات

+ +

تعلم البرمجة باستخدام الجافاسكربت من خلال الدورات والدروس الإرشاديّة التالية.

+ +

للمبتدئين

+ +

اطلع على قسم مواضيع تعلم الجافاسكربت إذا كنت ترغب بتعلم الجافاسكربت ولكنك لا تملك أي معرفة مسبقة بهاته اللغة أو بالبرمجة ككل. الوحدات المتوفرة هي:

+ +
+
الخطوات الأولى مع الجافاسكربت
+
تجيب هذه المقالة عن بعض الأسئلة الأساسيّة، مثل "ما هي الجافاسكربت؟"، "كيف تبدو هذه اللغة؟"، "ماذا بإمكانها أن تفعل؟"، بالإضافة إلى مناقشة بعض الميزات الأساسيّة للغة مثل المتغيّرات، السلاسل النصية، الأرقام، والمصفوفات.
+
البنى الكتليّة في اللغة
+
نكمل رحلتنا في تغطيّة المفاهيم الأساسية في لغة الجافاسكربت، ففي هذه المقالة قمنا بالتركيز على البنى الكتليّة الشائعة في اللغة مثل الجمل الشرطيّة، الحلقات، الدوال، والأحداث.
+
+ +

دليل لغة جافا سكربت

+ +
+
دليل اللغة
+
دليل أكثر تفصيلاً حول لغة الجافاسكربت، فهو موجه للذين يمتلكون معرفة مسبقة، سواءً بلغة الجافا سكربت، أو بلغات البرمجة الأخرى.
+
+ +

مقالات لذوي الخبرة المتوسطة

+ +
+
مقدمة إلى الكائنات
+
من المهم فهم البرمجة الشيئيّة في اللغة إذا أردت زيادة معرفتك والتمكن من كتابة شيفرة برمجيّة أكثر فعاليّة، من أجل ذلك قمنا بتوفير هذه الوحدة لك.
+
واجهات التصميم (جهة العميل) البرمجيّة
+
لن تستطيع العمل جيداً عند تطوير جهة المستخدم (client-side) باستخدام الجافاسكربت من دون تعلمك للواجهات البرمجيّة المتخصصة، فهي واجهات للتلاعب بأجزاء مختلفة من المُتصفِح ونظام التشغيل الذي يعمل عليه الموقع، أو حتى التلاعب بحقول بيانات مواقع أو خدمات أخرى. في هذه الوحدة سنستكشف ماهيّة هذه الواجهات، وكيف تستخدم بعض من أكثر تلك الواجهات شيوعاً والتي ستحتاجها غالباً في عملك.
+
+ +
+
نظرة عامة على الجافاسكربت
+
مقالة تقدم نظرة عامة للذين يظنون أنهم يعرفون الجافاسكربت.
+
+ +
+
هياكل بيانات الجافاسكربت
+
نظرة عامة على هياكل البيانات المتوفرة في اللغة.
+
عبارات المساواة والتطابق
+
توفر الجافاسكربت ثلاثة عمليات مساواة مختلفة: المساواة الصارمة باستخدام === والمساواة المتساهلة باستخدام == والدالة  {{jsxref("Global_Objects/Object/is", "Object.is()")}}.
+
+ +

مقالات متقدمة

+ +
+
الميراث وسلسلة النموذج الأولي
+
شرح الميراث القائم على النموذج الأولي الذي يساء فهمه على نطاق واسع.
+
الوضع الصارم
+
في الوضع الصارم (strict mode)، لا يمكنك استخدام أي متغيّر قبل تعريفه. فيعد الوضع الصارم البديل المحدود لـ ECMAScript 5، لأداء أسرع وأكثر سهولة في التنقيح.
+
مصفوفات الجافاسكربت المكتوبة
+
+
+
+
توفر مصفوفات الجافاسكربت المكتوبة (typed arrays) آلية للوصول إلى البيانات الثنائيّة.
+
+
+
+
إدارة الذاكرة
+
دورة حياة الذاكرة وجمع القمامة (garbage collection) في لغة الجافاسكربت.
+
نموذج التزامن وحلقة الحدث
+
تمتلك لغة الجافاسكربت نموذج تزامن قائم على مفهوم "حلقة الحدث (event loop)".
+
+
+ +
+

مرجع اللغة

+ +

تصفح مرجع لغة الجافاسكربت الشامل.

+ +
+
الكائنات القياسيّة
+
تعرف على الكائنات القياسيّة المبنيّة في اللغة {{jsxref("Array")}}، {{jsxref("Boolean")}}، {{jsxref("Date")}}، {{jsxref("Error")}}، {{jsxref("Function")}}، {{jsxref("JSON")}}، {{jsxref("Math")}}، {{jsxref("Number")}}، {{jsxref("Object")}}، {{jsxref("RegExp")}}، {{jsxref("String")}}، {{jsxref("Map")}}، {{jsxref("Set")}}، {{jsxref("WeakMap")}}، {{jsxref("WeakSet")}}، وغيرها الكثير.
+
التعابير والعمليات
+
تعلم المزيد حول وظيفة العمليات (operators) في الجافاسكربت {{jsxref("Operators/instanceof", "instanceof")}}، {{jsxref("Operators/typeof", "typeof")}}، {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}}، وغيرها الكثير.
+
الدوال
+
تعلم كيفيّة العمل مع الدوال في لغة الجافاسكربت لتطوير برمجياتك.
+
+ +

أدوات ومراجع

+ +

أدوات مفيدة لكتابة وتنقيح شيفرات الجافاسكربت.

+ +
+
أدوات مطورين فايرفوكس
+
أداة Scratchpad ،Web Console ،JavaScript Profiler ،Debugger، وغيرها الكثير.
+
صدفات الجافاسكربت
+
تسمح لك هذه الصدفات (shells) بالتجريب السريع لشيفرات الجافاسكربت.
+
أداة TogetherJS
+
التعاون يجعل الأمر سهلاً. بإضافة هذه الأداة لموقعك، سيتمكن المستخدمون من مساعدة بعضهم البعض على موقعك بشكل حي!
+
موقع Stack Overflow
+
الأسئلة الموسومة بالوسم "JavaScript" الموجودة على موقع Stack Overflow.
+
ملاحظات إصدار الجافاسكربت
+
تصفح سجل ميزات الجافاسكربت وحالة التقدم في التطوير.
+
أداة JSFiddle
+
قم بتعديل شيفرات الجافاسكربت، ولغة ترميز النص الفائق، وصفحات الأنماط الانسيابية واحصل على النتائج بشكل حي. استخدم موارد خارجيّة وتعاون مع أفراد فريقك على الأنترنت.
+
أداة Plunker
+
مجتمع على الإنترنت لإنشاء، والتعاون، ومشاركة أفكار تطوير الويب. قم بتعديل ملفات الجافاسكربت وغيرها من الملفات واحصل على النتائج بشكل حي.
+
+
+
diff --git a/files/ar/web/javascript/introduction_to_object-oriented_javascript/index.html b/files/ar/web/javascript/introduction_to_object-oriented_javascript/index.html new file mode 100644 index 0000000000..eab6c1edec --- /dev/null +++ b/files/ar/web/javascript/introduction_to_object-oriented_javascript/index.html @@ -0,0 +1,423 @@ +--- +title: مدخل إلى جافاسكريبت كائنية التوجه +slug: Web/JavaScript/Introduction_to_Object-Oriented_JavaScript +tags: + - الأفراد + - البرمجة الكائنية + - التغليف + - الجافاسكريبت + - المتوسط + - المجال + - المشيد + - ب.ك.ت + - كائن +translation_of: Learn/JavaScript/Objects +--- +
{{jsSidebar("Introductory")}}
+ +

كائنية التوجه حتى النخاع، ميزات جافا سكريبت القوية، القدرات المرنة {{Glossary("OOP")}}. يبدأ هذا المقال بمقدمة إلى البرمجة الكائنية التوجه، ثم مراجعات لنموذج كائن جافا سكريبت، و أخيراً يوضح مفاهيم البرمجة الكائنية التوجه في جافا سكريبت. لا يصف هذا المقال البناء اللغوي الجديد للبرمجة الكائنية التوجه في ECMAScript 6.

+ +
+

مراجعة جافا سكريبت

+ +

إذا كنت لا تشعر بالثقة حول مفاهيم جافا سكريبت مثل المتغيرات والأنواع والوظائف و المجال ، يمكنك ان تقرأ عن هذه المواضيع في مدخل إلى جافا سكريبت. يمكنك أيضا الاطلاع علي دليل جافا سكريبت.

+ +

البرمجة الكائنية التوجه (Object-oriented programming)

+ +

إن البرمجة الكائنية (OOP) ما هي إلا نمط برمجي يَستخدم التجريد في إنشاء نماذج/نسخ لتجسيد العالم الحقيقي، وتَستخدم البرمجة الكائنية في ذلك أساليب مُتعدّدة من هذا النمط، فهي تستخدم الوحدات module، وتعدديّة الأشكال polymorphism والتغليف encapsulation، وتجدر الإشارة إلى أن معظم لغات البرمجة تدعم مفهوم OOP أمثال اللغات البرمجية: جافا، بايثون، روبي، وطبعًا جافا سكريبت.

+ +

يُعالج أو لنقل يَتصور مفهوم البرمجة الكائنية OOP البرنامج كتشكيلة من الأشياء/الكائنات المتعاونة/المترابطة بدلًا من يتصوّره كتشكيلة من الدوال (functions) أو كسرد من الأوامر. ففي مفهوم OOP، كل كائن/شيء له القدرة على استقبال الرسائل، ومعالجة البيانات، وإرسال الرسائل إلى باقي الكائنات، ويُمكن اعتبار أنه لكل كائن object كينونة خاصة به ودور/وظيفة مستقلة عن الكائن الآخر.

+ +

تُعزز البرمجة الكائنية القدرة على صيانة الشيفرة البرمجية والمرونة في التطوير، وأثبتت جدارتها على نطاق واسع في هندسة البرمجيات الكبيرة، ولأن البرمجة الكائنية تُشدد على استخدام الوحدات module، فإن الشيفرة/الكود المكتوب بمفهوم البرمجة الكائنية هو أبسط في التطوير وأسهل في الفهم مستقبلًا (عند التنقيح والتعديل)، وكما يعزز مفهوم البرمجة الكائنية التحليل المباشر للشيفرة، وفهم الحالات الشائكة فهمًا أفضل من باقي الأساليب البرمجية الأخرى.

+ +

مصطلحات البرمجة الكائنية

+ +
+
+

المجال في البرمجة الكائنية Namespace

+ +

ما هو إلا عبارة عن حاوي تسمح للمطوّر بتحزيم جميع الوظائف تحت اسم محدد وفريد.

+ +

الصنف أو الفئة Class في البرمجة الكائنية

+ +

يعتني الصنف بكل ما يتعلّق بميزات وخصائص الكائن، والصنف ما هو إلا قالب template تعريفي بخاصيات properties وبطُرق/وظائف methods الكائن object.

+ +

الكائن Object في البرمجة الكائنية

+ +

الكائن ما هو إلا حالة/أمثولة instance من صنف class.

+ +

الخاصية property في البرمجة الكائنية

+ +

ما هي إلا مميزات وخصائص الكائن، كاللون مثلًا.

+ +

الطريقة أو الوظيفة Method في البرمجة الكائنية

+ +

تعتني الطريقة أو الوظيفة كما يُسميها البعض بقدرات الكائن، مثل قدرة المشي مثلًا، وهي دور أو وظيفة مرتبطة مع صنف class.

+ +

المشيد Constructor في البرمجة الكائنية

+ +

ما هو إلا طريقة method تُستدعى في لحظة استهلال instantiate الكائن، وعادةً ما يكون له نفس اسم الصنف الذي يحتويه.

+ +

الوراثة Inheritance في البرمجة الكائنية

+ +

يُمكن للصنف أن يرث مميزات من صنف آخر.

+ +

التغليف Encapsulation في البرمجة الكائنية

+ +

طريقة في تحزيم البيانات data والطُرق methods التي تستخدم البيانات.

+ +

التجريد Abstraction في البرمجة الكائنية

+ +

يجب على الاقتران الحاصل من: الوراثة والطُرق methods والخاصيات properties لكائن معقد وشائك التمثيل برمجيًا أن يعكس الواقع المراد محاكاته في البرمجة الكائنية.

+ +

تعددية الأشكال Polymorphism في البرمجة الكائنية

+ +

تحمل كلمة Poly بحد ذاتها المعنى "متعدد" وتحمل الكلمة morphism المعنى "أشكال، ويُشير المفهوم ككل إلى أن أكثر من صنف قد يُعرّف نفس الطريقة method أو الخاصية property.

+
+
+ +

للحصول على وصف أكثر شمولية للبرمجة الكائنية التوجه، أنظر {{interwiki("wikipedia", "البرمجة كائنية التوجه")}} على ويكيبيديا.

+ +

البرمجة المعتمدة على النموذج الأولي Prototype

+ +

البرمجة المعتمدة على النموذج الأوّلي (Prototype-based programming) ما هي إلا نموذج من البرمجة الكائنية OOP ولكنها لا تستخدم الأصناف classes، بل تقوم أولًا بإعداد سلوك أي صنف class ما ومن ثم تُعيد استخدامه، ويُطلق البعض على هذا النموذج: البرمجة بلا أصناف classless، أو البرمجة المَبْدَئِية المنحى prototype-oriented، أو البرمجة المعتمدة على الأمثولة instance-based).

+ +

يعود أصل اللغة المعتمدة على النموذج الأولي إلى لغة Self، والتي طوّرها David Ungar وRandall Smith، ولكن أسلوب البرمجة بدون أصناف class-less توسّع ونال شهرة كبيرة في العقد الأخير، واُعتمد من قبل العديد من اللغات البرمجية أشهرهم جافا سكريبت.

+ +

 

+ +

البرمجة الكائنية باستخدام جافا سكريبت

+ +

المجال Namespace في جافا سكريبت

+ +

المجال هو أشبه بمستوعب/بحاوية (container) تسمح للمطوّر في تحزيم وظائف تحت اسم فريد، أو اسم تطبيق محدد، ففي جافا سكريبت المجال هو مجرد كائن object كأي كائن آخر يحتوي على طُرق methods، وخاصيات properties، وحتى كائنات objects.

+ +
+

ملاحظة هامة: من المهم جدًا الانتباه إلى أنه في جافا سكريبت، لا يوجد فرق بين الكائنات العادية والمجالات namespaces، وهذا يختلف عن اللغات الكائنية الأخرى، الأمر الذي قد يُربك المبرمجين المبتدئين في جافا سكريبت.

+
+ +

إن إنشاء مجال namespace في جافا سكريبت بسيطٌ للغاية، فمن خلال إنشاء كائن عام/مشترك/شامل global، ستصبح جميع المُتغيّرات variables والطرق methods، والدوال functions خاصياتٍ لهذا الكائن، ويٌقلل استخدام المجالات namespaces أيضًا من احتمالية تضارب الأسماء في التطبيق، منذ أن كل كائن من كائنات التطبيق ما هي إلى خاصيات كائن شامل/عام معرّفة على مستوى التطبيق.

+ +

سيُنشئ في الخطوة التالية كائنًا عامًا global وبالاسم MYAPP:

+ +
// مجال عالمي
+var MYAPP = MYAPP || {};
+ +

يُظهر المثال السابق، كيف تم التأكّد أولًا فيما إذا كان MYAPP معرفًا (سواء في نفس الملف أو في آخر)، ففي حال الإيجاب سيُستخدم الكائن العام MYAPP، وفي حال عدم تعريفه مُسبقًا سيُنشئ كائنًا خالٍ وبالاسمMYAPP والذي سيغلّف encapsulate الطرق methods والدوال functions والمتغيرات variables والكائنات objects.

+ +

كما يُمكن أيضًا إنشاء مجال فرعي sub-namespaces:

+ +
// مجال فرعي
+MYAPP.event = {};
+ +

يوضّح المثال التالي الصيغة المستخدمة في إنشاء مجال namespace وإضافة متغيرات ودوال:

+ +
// إنشاء حاوي يدعى MYAPP.commonMethod للوظائف و الخصائص الشائعة
+MYAPP.commonMethod = {
+  regExForName: "", // تعريف تعبير نظامي للتحقق من الإسم
+  regExForPhone: "", // تعريف تعبير نظامي للهاتف، لا يوجد تحقق من الصحة
+  validateName: function(name){
+    // إفعل شيئا ما بالإسم، يمكنك الوصول إلى المتغير regExForName
+    // بإستعمال "this.regExForName"
+  },
+
+  validatePhoneNo: function(phoneNo){
+    // إفعل شيئا ما برقم الهاتف
+  }
+}
+
+// تعريفات الكائن مع الزظيفة في نفس الوقت
+MYAPP.event = {
+    addListener: function(el, type, fn) {
+    // بعض الأكواد
+    },
+    removeListener: function(el, type, fn) {
+    // بعض الأكواد
+    },
+    getEvent: function(e) {
+    // بعض اﻷكواد
+    }
+
+    // يمكن إضافة وظائف و خصائص أخرى
+}
+
+// البناء اللغوي لإستعمال وظيفة addListener:
+MYAPP.event.addListener("yourel", "type", callback);
+ +

 

+ +

الكائنات الأساسية/القياسية المبنية داخل لغة جافا سكريبت (Standard built-in objects)

+ +

تتضمن لغة جافا سكريبت العديد من الكائنات في تركيبتها، على سبيل المثال، يوجد كائنات مثل Math،Object، Array، String، ويُظهر المثال التالي كيفيّة استخدام الكائن Math للحصول على رقم عشوائي باستخدام أحد طُرق method هذا الكائن وهي الطريقة ()random.

+ +
console.log(Math.random());
+
+ +
+

ملاحظة: يَفترض المثال السابق وجميع الأمثلة التالية في المقال وجود دالة function بالاسم()console.log معرّفة تعريفًا عامًا (globally)، مع العلم أن هذه الدالة ليست جزء من اللغة نفسها، ولكنها دالة متوفّرة في العديد من متصفحات الإنترنت لأغراض تشخيص الشيفرة البرمجية debugging.

+
+ +

يُمكن العودة إلى مرجع لغة جافا سكريبت: الكائنات الأصلية المعيارية للحصول على قائمة بالكائنات المبينة داخل لغة جافا سكريبت نفسها.

+ +

كل كائن في جافا سكريبت هو حالة/أمثولة instance من الكائن Object ويَرث كافة خاصياته properties وطُرقه methods.

+ +

 

+ +

الكائنات الخاصة
+ الصنف (الفئة)

+ +

لغة جافا سكريبت لغة من النوع prototype-based ولا تحتوي على العبارة class كما هو حال باقي لغات البرمجة الكائنية، كما في روبي أو بايثون، ويُربك هذا الأمر المبرمجين المعتادين على اللغات التي تعتمد على هذه العبارة أو المفهوم، وتستخدم جافا سكريبت بدلًا من ذلك الدوال functions لمحاكات مفهوم الأصناف classes، وتعريف صنف هو بسهولة تعريف أي دالّة:

+ +
var Person = function () {};
+
+ +

الكائن (أمثولة الصنف class instance)

+ +

يتطلب إنشاء حالة/أمثولة instance جديدة من كائن obj استخدام العبارة new obj، وتعيين النتيجة إلى متغيّر بغرض الوصول إلى فيما بعد.

+ +

عُرّف في الشيفرة السابقة صنف class بالاسم Person، وفي الشيفرة التالية، سيُنشئ حالتين/أمثولتين instances من هذا الصنف، الأولى بالاسم person1 والثانية بالاسم person2.

+ +
var person1 = new Person();
+var person2 = new Person();
+
+ +
فضلا أنظر {{jsxref("Object.create()")}} للحصول على وظيفة الإنشاء الجديدة الإضافية التي تنشأ حالة غير مهيأة
+ +

المشيد The constructor

+ +

يُستدعى المُشيّد constructor في لحظة الاستهلال instantiation (اللحظة التي يُنشئ فيها الكائن)، والمُشيّد ما هو إلا طريقة method من طُرق الصنف class، وفي جافا سكريبت تعمل الدالة على تشييد الكائن، ولذلك لا داعي إلى تعريف طريقة method من أجل عميلة التشييد، وكل إجراء مصرّح في الصنف class يُنفّذ في لحظة الاستهلال instantiation.

+ +

يُستخدم المُشيّد في تعيين خاصيات properties الكائن، أو في استدعاء طُرق methods معينة لتحضير الكائن للاستخدام، وأما إضافة طُرق صنف وتعريفها يحدث باستخدام صيغة syntax مختلفة سنتطرّق إليها فيما بعد خلال المقال.

+ +

تُظهر الشيفرة التالية كيف يُسجّل log (يُرسل رسالة نصية إلى طرفية المتصفح console) مُشيّد الصنفPerson رسالة نصية حينما يُستهل instantiated.

+ +
var Person = function () {
+  console.log('تم إنشاء حالة');
+};
+
+var person1 = new Person();
+var person2 = new Person();
+
+
+ +

الخاصية The property (خاصية الكائن object attribute)

+ +

الخاصيات properties ما هي إلا متغيرات محتوات في الصنف class، وكل حالة/أمثولة من الكائن تمتلك هذه الخاصيات، وتُعيّن الخاصيات في دالة مُشيّد الصنف بحيثُ تُنشئ مع كل حالة/أمثولة instance.

+ +

إن الكلمة المفتاحية this، والتي تُشير إلى الكائن الحالي، تسمح للمطوّر بالعمل مع الخاصيات من ضمن الصنف، والوصول (قراءةً وكتابةً) إلى الخاصية property من خارج الصنف يكون من خلال الصيغةInstanceName.Property كما هو الأمر في لغة C++ (سي بلس بلس) وJava والعديد من اللغات الأخرى، ومن داخل الصنف تُستخدم الصيغة this.Property للحصول على قيمة الخاصية أو لتعيين قيمتها.

+ +

في الشيفرة التالية، عُرّفت الخاصية firstName للصنف Person وفي لحظة الاستهلال instantiation:

+ +
var Person = function (firstName) {
+  this.firstName = firstName;
+  console.log('تم إنشاء حالة من Person');
+};
+
+var person1 = new Person('سفيان');
+var person2 = new Person('محمد');
+
+// Show the firstName properties of the objects
+console.log('الشخص1 هو ' + person1.firstName); // النتيجة ==> "الشخص1 هو سفيان"
+console.log('الشخص2 هو ' + person2.firstName); // النتيجة ==> "الشخص2 هو محمد"
+
+ +

الطرق The methods

+ +

الطرق methods ما هي إلا دوال (وتُعرّف كما تعرّف الدوال functions)، فيما عدا ذلك فهي تُشبه الخاصيات properties، واستدعاء طريقة method مشابه إلى الوصول إلى خاصيّة ما، ولكن مع إضافة () في نهاية اسم الطريقة، وربما مع مُعطيات arguments، ولتعريف طريقة، تُعيّن دالة إلى خاصيّة مُسمّات من خاصيّة الصنف prototype، ويُمكن فيما بعد استدعاء الطريقة على الكائن بنفس الاسم الذي عُيّن للدالة.

+ +

في الشيفرة التالية، عُرّفت ومن ثم اُستخدِمت الطريقة ()sayHello للصنف Person.

+ +
var Person = function (firstName) {
+  this.firstName = firstName;
+};
+
+Person.prototype.sayHello = function() {
+  console.log("مرحبا، أنا " + this.firstName);
+};
+
+var person1 = new Person("سفيان");
+var person2 = new Person("محمد");
+
+// إستدعاء طريقة Person sayHello.
+person1.sayHello(); // النتيجة ==>"مرحبا، أنا سفيان"
+person2.sayHello(); // النتيجة ==> "مرحبا، أنا محمد"
+
+ +

إن الطُرق methods في جافا سكريبت ما هي إلا دالة كائن عادية مرتبطة مع كائن كخاصية property، وهذا يعني أنه يُمكن استدعاء الطُرق خارج السياق، كما في المثال التالي:

+ +
var Person = function (firstName) {
+  this.firstName = firstName;
+};
+
+Person.prototype.sayHello = function() {
+  console.log("مرحبا، أنا " + this.firstName);
+};
+
+var person1 = new Person("سفيان");
+var person2 = new Person("محمد");
+var helloFunction = person1.sayHello;
+
+// النتيجة ==> "مرحبا، أنا سفيان"
+person1.sayHello();
+
+// النتيجة ==> "مرحبا، أنا محمد"
+person2.sayHello();
+
+// النتيجة ==> "مرحبا، أنا undefined" (أو أخطاء
+// TypeError في الوضع الصارم)
+helloFunction();
+
+// النتيجة ==> true
+console.log(helloFunction === person1.sayHello);
+
+// النتيجة ==> true
+console.log(helloFunction === Person.prototype.sayHello);
+
+// النتيجة ==> "مرحبا، أنا سفيان"
+helloFunction.call(person1);
+ +

كما يُظهر المثال السابق، جميع الإحالات المستخدمة في استدعاء الدالة sayHello تُشير إلى نفس الدالةسواءً الاستدعاء الحاصل مع person1 أو Person.prototype أو حتى في المتغيّر helloFunctionوقيمة this خلال استدعاء الدالة يعتمد على الكيفية التي تُستدعى فيها، حيث تُشير الكلمة المفتاحيةthis إلى الكائن الحالي الذي تُستدعى عليه الطريقة method، بمعنى عندما تم استدعاء الطريقة()sayHello على الكائن person1 فإن this تُشير إلى الكائن person1، وعند استدعاء sayHelloعلى الكائن person2 فإن this تُشير إلى الكائن person2، ولكن إن تم الاستدعاء بطريقة مختلفة، فإنthis ستُعيّن تعينًا مختلفًا، فاستدعاء this من المتغيّر (كما في ()helloFunction) سيُعيّن this إلى الكائن العام global (والذي سيكون window في متصفح الإنترنت)، ومنذ أن هذا الكائن (على الأغلب) لا يملك الخاصّيّة firstName، ستكون النتيجة كما هو الحال في المثال السابق “Hello, I’m undefined”، كما يمكن دائمًا تعيين this صراحةً باستخدام Function#call (أو Function#apply) وهو كما كان في نهاية المثال.

+ +
ملاحظة: أنظر المزيد حول this على call و apply
+ +

الوراثة

+ +

تُستخدم الوراثة في جافا سكريبت في إنشاء صنف class كمثيل مخصص لصنف أو أكثر (تدعم جافا سكريبت وراثة وحيدة فقط single inheritance)، ويُطلق على الصنف المخصص عادةً ابن (child)، ويطلق على الصنف الآخر عادةً  الأب (parent)، وفي جافا سكريبت يتمّ ذلك من خلال إسناد حالة/أمثولة من الصنف الأب إلى الصنف الابن، ومن ثم تخصيصه، وفي متصفحات الإنترنت الحديثة يُمكن استخدامObject.create في تحقيق الوراثة inheritance أيضًا.

+ +
+

ملاحظة: لا تتفقد جافا سكريبت مُشيّد صنف الابن prototype.constructor (راجعObject.prototype)، وعليه يجب التصريح عن ذلك يدويًا، لمزيد من التفصيل راجع السؤال التالي علىStackoverflow.

+
+ +

عُرّف في الشيفرة التالية الصنف Student كصنف ابن للصنف Person، ومن ثم أُعيد تعريف الطريقة()sayHello وأُضيفت الطريقة ()sayGoodBye علاوة على ذلك.

+ +
// تعريف المشيد Person
+var Person = function(firstName) {
+  this.firstName = firstName;
+};
+
+// إضافة زوج من الطرق إلى Person.prototype
+Person.prototype.walk = function(){
+  console.log("أنا أتمشى!");
+};
+
+Person.prototype.sayHello = function(){
+  console.log("مرحبا، أنا " + this.firstName);
+};
+
+// تعريف مشيد Student
+function Student(firstName, subject) {
+  // إستدعاء المشيد اﻷب, التأكد (عن طريق الإستدعاء)
+  // من أن "this" وضعت بشكل صحيح أثناء اﻹستدعاء
+  Person.call(this, firstName);
+
+  // تهيئة خصائص الطالب المحددة
+  this.subject = subject;
+}
+
+// إنشاء كائن Student.prototype الذي يرث من Person.prototype.
+// ملاحظة: خطأ شائع أن يستعمل "new Person()" ﻹنشاء
+// Student.prototype. هذا غير صحيح لعدة أسباب،
+// ليس أقل أننا ليس لدينا أي شيء ﻹعطاء Person إلى المعامل "firstName".
+// الطريقة الصحيحة ﻹستدعاء Person هي في الأعلى حيث
+// إستدعيناه من Student.
+Student.prototype = Object.create(Person.prototype); // See note below
+
+// وضع الخاصية "constructor" للإشارة إلى Student
+Student.prototype.constructor = Student;
+
+// إستبدال الطريقة "sayHello"
+Student.prototype.sayHello = function(){
+  console.log("مرحبا، أنا " + this.firstName + ". أنا أدرس "
+              + this.subject + ".");
+};
+
+// إضافة الطريقة "sayGoodBye"
+Student.prototype.sayGoodBye = function(){
+  console.log("وداعا!");
+};
+
+// إستعمال المثال:
+var student1 = new Student("سفيان", "المناجم");
+student1.sayHello();   // "مرحبا، أنا سفيان. أنا أدرس المناجم."
+student1.walk();       // "أنا أتمشى!"
+student1.sayGoodBye(); // "وداعا!"
+
+// التحقق من أن instanceof يعمل بشكل صحيح
+console.log(student1 instanceof Person);  // true
+console.log(student1 instanceof Student); // true
+
+ +

فيما يخص السطر ;(Student.prototype = Object.create(Person.prototype في الإصدارات القديمة من جافا سكريبت والتي لا تدعم Object.create يمكن إما استخدام بعض الحيل في خداع المتصفحات –هذه الخدع معروفة إما بالاسم polyfill أو shim—أو استخدام دالة تحقق نفس النتيجة كما في المثال التالي:

+ +
function createObject(proto) {
+    function ctor() { }
+    ctor.prototype = proto;
+    return new ctor();
+}
+
+// الإستعمال:
+Student.prototype = createObject(Person.prototype);
+
+ +
ملاحظة: أنظر Object.create للمزيد من المعلومات حول ما يقوم به, و الرقاقات للمحركات القديمة.
+ +

التأكّد من أن this تُشير إلى الكائن المطلوب بغض النظر عن كيف للكائن أن يُستهل يمكن أن يكون صعبًا، ومع ذلك يوجد صياغة أبسط من شأنها أن تسهّل الأمر.

+ +
var Person = function(firstName) {
+  if (this instanceof Person) {
+    this.firstName = firstName;
+  } else {
+    return new Person(firstName);
+  }
+}
+
+ +

التغليف Encapsulation

+ +

ليس بالضرورة أن يعلم الصنف Student كيف تمّ تنفيذ/تعريف الطريقة ()walk للصنف Person لكي يستطيع استخدام تلك الطريقة، ولا يحتاج الصنف Student إلى تعريف تلك الطريقة صراحةً إلا إذا كان المطلوب التعديل عليها، ويُطلق على هذا الإجراء مفهوم التغليف encapsulation، والذي فيه يَحزم كل صنف البيانات والطُرق methods داخل وحدة/كينونة وحيدة.

+ +

إخفاء المعلومات سمة شائعة في باقي اللغات البرمجية وعادةً ما توجد كخاصيات/كطُرق إما بالاسمprivate أو protected، وعلى الرغم من أنه يُمكن مماثلة/محاكاة ذات الأمر في جافا سكريبت، إلا أن هذا الأمر ليس مطلبًا من متطلبات البرمجة الكائنية.

+ +

التجريد Abstraction

+ +

التجرير ما هو إلا ميكانيكية تسمح للمطوّر في تجسيد جانب من المشكلة التي يُعمل عليها، إما من خلال الوراثة inheritance (التخصيص specialization) أو التركيب composition، وتُحقق جافا سكريبت التخصيص من خلال الوراثة، والتركيب من خلال السماح لحالات/أمثولات الصنف لتكون قيمًا لخاصيات attributes الكائنات الأخرى.

+ +

الصنف Function في جافا سكريبت يرث من الصنف Object (وهذا يوضّح التخصيص في هذا النموذج) والخاصية Function.prototype ما هي إلا حالة/أمثولة من الصنف Object (وهذا يوضّح جزئية التركيب composition).

+ +
var foo = function () {};
+
+// النتيجة ==> "foo عبارة عن وظيفة: true"
+console.log('foo عبارة عن وظيفة: ' + (foo instanceof Function));
+
+// النتيجة ==> "foo.prototype عبارة عن كائن: true"
+console.log('foo.prototype عبارة عن كائن: ' + (foo.prototype instanceof Object));
+ +

تعددية الأشكال Polymorphism

+ +

كما أن جميع الطُرق methods والخاصيات properties معرّفة ضمن الخاصية prototype، فيُمكن لبقية الأصناف أن تُعرِّف طُرقًا methods بنفس الاسم، وستكون الطُرق في نطاق الصنف الذي عُرفت به، إلا إذا كان الصنفان على علاقة من نوع أب وابن parent-child، بمعنى آخر أحد الصنفان يرث من الآخر
+
+ هذه المقالة تُرجمة الي العربية بواسطة : محمد أبرص

+ +

ملاحظات

+ +

هذه ليست الطرق الوحيدة التي يمكنك من خلالها تنفيذ البرمجة الشيئية في جافا سكريبت ، والتي تعد مرنة للغاية في هذا الصدد. وبالمثل ، فإن التقنيات الموضحة هنا لا تستخدم أي لغة خارقة ، ولا تحاكي تطبيقات اللغات الأخرى لنظرية الكائن.

+ +

هناك تقنيات أخرى تجعل البرمجة الكائنية التوجه أكثر تقدما لكنها خارج نطاق الهذه المقالة التمهيدية.

+
+ +

المراجع

+ +
    +
  1. ويكيبيديا - البرمجة الكائنية التوجه
  2. +
  3. ويكيبيديا - البرمجة القائمة على النوذج
  4. +
  5. ويكيبيديا - التغليف (البرمجة الكائنية التوجه)
  6. +
+ +

أنظر أيضا

+ + diff --git a/files/ar/web/javascript/reference/classes/constructor/index.html b/files/ar/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..135948c80b --- /dev/null +++ b/files/ar/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,132 @@ +--- +title: المنشئ (constructor) +slug: Web/JavaScript/Reference/Classes/constructor +tags: + - جافاسكريبت +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +
{{jsSidebar("Classes")}}
+ +

الـ constructor  هي ميثود خاصة لإنشاء وتهيئة الاوبجكت(كائن) داخل (فئة)class.

+ +
{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}
+ + + +

بناء الجملة

+ +
constructor([arguments]) { ... }
+ +

الوصف

+ +

يمكننا إستخدام تلك الميثود لمرة واحده فقط ، وفي حال إستخدمنا constructor ﻷكثر من مرة في نفس الفئة الـ class سيحدث {{jsxref("SyntaxError")}} إيرور .

+ +

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

+ +

إذا لم تحدد ميثود إنشاء سيتم تحديد منشئ بشكل تلقائي.

+ +


+ If you do not specify a constructor method, a default constructor is used.

+ +

أمثلة

+ +

إٍستخدام الميثود (اسلوب) الـconstructor

+ +

ذلك الكود تم أخذه ولصقة من classes sample (live demo)

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Here, it calls the parent class' constructor with lengths
+    // provided for the Polygon's width and height
+    super(length, length);
+    // Note: In derived classes, super() must be called before you
+    // can use 'this'. Leaving this out will cause a reference error.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

مثال آخر

+ +

إنظر إلى ذلك الكود

+ +
class Polygon {
+    constructor() {
+        this.name = "Polygon";
+    }
+}
+
+class Square extends Polygon {
+    constructor() {
+        super();
+    }
+}
+
+class Rectangle {}
+
+Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
+
+console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
+console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true
+
+let newInstance = new Square();
+console.log(newInstance.name); //Polygon
+ +

هنا البروتوتيب فئة الـ Square تغيرت ولكن الكونستركتور (المنشئ) مبني على فئة الـPolygon والتي تطلب عندما نقوم بإنشاء حالة مماثلة للـ Square مرة أخرى

+ +

الإنشاء الإفتراضي

+ +

ذكرنا سابقا أنه في حال عدم تحديدك لكونستركتور (منشئ) سيتم تحديد الكونستركتور بشكل إفتراضي ، وبالنسبة للكلاسز (الفئات) الاولية يكون الكونستركتور الخاص بها كما يلي :-

+ +
constructor() {}
+
+ +

أما الفئات المشتقة فتكون بالشكل التالي

+ +
constructor(...args) {
+  super(...args);
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.classes.constructor")}}

+ +

أنظر أيضا

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

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.

+ +

Defining classes

+ +

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

+ +

Class declarations

+ +

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

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

Hoisting

+ +

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

+ +
var p = new Rectangle(); // ReferenceError
+
+class Rectangle {}
+
+ +

Class expressions

+ +

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

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

Note: Class expressions also suffer from the same hoisting issues mentioned for Class declarations.

+ +

Class body and method definitions

+ +

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

+ +

Strict mode

+ +

The bodies of class declarations and class expressions are executed in strict mode i.e. constructor, static and prototype methods, getter and setter functions are executed in strict mode.

+ +

Constructor

+ +

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

+ +

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

+ +

Prototype methods

+ +

See also method definitions.

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

Static methods

+ +

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

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

Boxing with prototype and static methods

+ +

When a static or prototype method is called without a value for this, the this value will be undefined inside the method. This behavior will be the same even if the "use strict" directive isn't present, because code within the class syntax is always executed in strict mode.

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

If the above is written using traditional function–based syntax, then autoboxing in method calls will happen in non–strict mode based on the initial this value. If the inital value is undefined, this will be set to the global object.

+ +

Autoboxing will not happen in strict mode, the this value remains as passed.

+ +
function Animal() { }
+
+Animal.prototype.speak = function() {
+  return this;
+}
+
+Animal.eat = function() {
+  return this;
+}
+
+let obj = new Animal();
+let speak = obj.speak;
+speak(); // global object
+
+let eat = Animal.eat;
+eat(); // global object
+
+ +

Instance properties

+ +

Instance properties must be defined inside of class methods:

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

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

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

 

+ +

Sub classing with extends

+ +

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

+ +
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+var d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+ +

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

+ +

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

+ +
function Animal (name) {
+  this.name = name;
+}
+
+Animal.prototype.speak = function () {
+  console.log(this.name + ' makes a noise.');
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+var d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+ +

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

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

Species

+ +

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

+ +

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

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

Super class calls with super

+ +

The super keyword is used to call corresponding methods of super class.

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

Mix-ins

+ +

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

+ +

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

+ +
var calculatorMixin = Base => class extends Base {
+  calc() { }
+};
+
+var randomizerMixin = Base => class extends Base {
+  randomize() { }
+};
+
+ +

A class that uses these mix-ins can then be written like this:

+ +
class Foo { }
+class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.classes")}}

+ +

Running in Scratchpad

+ +

A class can't be redefined. If you're playing with code in Scratchpad (Firefox menu Tools > Web Developer > Scratchpad) and you 'Run' a definition of a class with the same name twice, you'll get a confusing SyntaxError: redeclaration of let <class-name>.

+ +

To re-run a definition, use Scratchpad's menu Execute > Reload and Run.
+ Please vote for bug #1428672.

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/errors/index.html b/files/ar/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/ar/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

+ +

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

+ +

List of errors

+ +

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

+ +

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/errors/unexpected_type/index.html b/files/ar/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..085dc8a167 --- /dev/null +++ b/files/ar/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,68 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - الأخطاء + - جافاسكربت + - نوع الخطأ +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +
{{jsSidebar("Errors")}}
+ +

الرسالة

+ +
TypeError: Unable to get property {x} of undefined or null reference (Edge)
+TypeError: "x" is (not) "y" (Firefox)
+
+Examples:
+TypeError: "x" is undefined
+TypeError: "x" is null
+TypeError: "undefined" is not an object
+TypeError: "x" is not an object or null
+TypeError: "x" is not a symbol
+
+ +

نوع الخطأ

+ +

{{jsxref("TypeError")}}.

+ +

 ماذا حصل؟

+ +

خطأ غير متوقع، يحدث كثيرا مع {{jsxref("undefined")}} أو قيم {{jsxref("null")}} .

+ +

أيضا في بعض الوضائف مثل {{jsxref("Object.create()")}} أو {{jsxref("Symbol.keyFor()")}}, تحتاج تقديد أنواع محددة.

+ +

أمثلة

+ +

حالات غير صحيحة

+ +
// undefined and null cases on which the substring method won't work
+var foo = undefined;
+foo.substring(1); // TypeError: foo is undefined
+
+var foo = null;
+foo.substring(1); // TypeError: foo is null
+
+
+// Certain methods might require a specific type
+var foo = {}
+Symbol.keyFor(foo); // TypeError: foo is not a symbol
+
+var foo = 'bar'
+Object.create(foo); // TypeError: "foo" is not an object or null
+
+ +

حل المشكلة

+ +

لإصلاح مؤشر null إلى قيم undefined أو null ، يمكنك استخدام عامل التشغيل typeof ، على سبيل المثال.

+ +
if (typeof foo !== 'undefined') {
+  // الآن نعلم أن القيمة المدخلة غير محددة، نستطيع القيام بأي إجراء بدون خطأ.
+}
+ +

شاهد أيضاً

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/index.html b/files/ar/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..1e00adcf73 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,481 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +
كائن Array في جافاسكربت  هو كائن عام، يستخدم في إنشاء المصفوفات، وهي تشبه قائمة من الكائنات عالية المستوى.
+ +
 
+ +

إنشاء مصفوفة

+ +
var fruits = ["Apple", "Banana"];
+
+console.log(fruits.length);
+// 2
+
+ +

الوصول إلى عنصر محدد في المصفوفة

+ +
var first = fruits[0];
+// Apple
+
+var last = fruits[fruits.length - 1];
+// Banana
+
+ +

تنفيذ حلقة تكرار على مصفوفة

+ +
fruits.forEach(function (item, index, array) {
+  console.log(item, index);
+});
+// Apple 0
+// Banana 1
+
+ +

إلحاق عنصر بآخر المصفوفة

+ +
var newLength = fruits.push("Orange");
+// ["Apple", "Banana", "Orange"]
+
+ +

حذف عنصر من نهاية المصفوفة

+ +
var last = fruits.pop(); // remove Orange (from the end)
+// ["Apple", "Banana"];
+
+ +

حذف عنصر من بداية المصفوفة

+ +
var first = fruits.shift(); // remove Apple from the front
+// ["Banana"];
+
+ +

إضافة عنصر إلى بداية المصفوفة

+ +
var newLength = fruits.unshift("Strawberry") // add to the front
+// ["Strawberry", "Banana"];
+
+ +

الوصول إلى ترتيب عنصر معينة في المصفوفة

+ +
fruits.push("Mango");
+// ["Strawberry", "Banana", "Mango"]
+
+var pos = fruits.indexOf("Banana");
+// 1
+
+ +

حذف عنصر عن طريق ترتيبه في المصفوفة

+ +
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
+// ["Strawberry", "Mango"]
+
+ +

نسخة مصفوفة

+ +
var shallowCopy = fruits.slice(); // this is how to make a copy
+// ["Strawberry", "Mango"]
+
+ +

Syntax

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +

Parameters

+ +
+
elementN
+
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below).Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
+
arrayLength
+
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
+
+ +

الوصف

+ +

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

+ +

Some people think that you shouldn't use an array as an associative array. In any case, you can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post Lightweight JavaScript dictionaries with arbitrary keys as an example.

+ +

الوصول إلى عناصر المصفوفة

+ +

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.

+ +
var arr = ['this is the first element', 'this is the second element'];
+console.log(arr[0]);              // logs 'this is the first element'
+console.log(arr[1]);              // logs 'this is the second element'
+console.log(arr[arr.length - 1]); // logs 'this is the second element'
+
+ +

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:

+ +
console.log(arr.0); // a syntax error
+
+ +

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

+ +
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
+console.log(years.0);   // a syntax error
+console.log(years[0]);  // works properly
+
+ +
renderer.3d.setTexture(model, 'character.png');     // a syntax error
+renderer['3d'].setTexture(model, 'character.png');  // works properly
+
+ +

Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is for this reason that '2' and '02' would refer to two different slots on the years object and the following example could be true:

+ +
console.log(years['2'] != years['02']);
+
+ +

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation(but it can be accessed by dot notation in firefox 40.0a2 at least):

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['array']);
+
+ +

Relationship between length and numerical properties

+ +

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

+ +
var fruits = [];
+fruits.push('banana', 'apple', 'peach');
+
+console.log(fruits.length); // 3
+
+ +

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

+ +
fruits[5] = 'mango';
+console.log(fruits[5]); // 'mango'
+console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
+console.log(fruits.length); // 6
+
+ +

Increasing the {{jsxref("Array.length", "length")}}.

+ +
fruits.length = 10;
+console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
+console.log(fruits.length); // 10
+
+ +

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

+ +
fruits.length = 2;
+console.log(Object.keys(fruits)); // ['0', '1']
+console.log(fruits.length); // 2
+
+ +

This is explained further on the {{jsxref("Array.length")}} page.

+ +

Creating an array using the result of a match

+ +

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

+ +
// Match one d followed by one or more b's followed by one d
+// Remember matched b's and the following d
+// Ignore case
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

The properties and elements returned from this match are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
+ [2]: d
+ +

الخصائص

+ +
+
Array.length
+
The Array constructor's length property whose value is 1.
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Array.prototype")}}
+
Allows the addition of properties to all array objects.
+
+ +

الدوال

+ +
+
{{jsxref("Array.from()")}}
+
Creates a new Array instance from an array-like or iterable object.
+
{{jsxref("Array.isArray()")}}
+
Returns true if a variable is an array, if not false.
+
{{jsxref("Array.of()")}}
+
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
+
+ +

Array instances

+ +

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

+ +

الخصائص

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
+ +

الدوال

+ +

Mutator methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
+ +

Accessor methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
+ +

Iteration methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
+ +

Array generic methods

+ +
+

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

+
+ +

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

+ +
function isLetter(character) {
+  return character >= 'a' && character <= 'z';
+}
+
+if (Array.prototype.every.call(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

+ +
if (Array.every(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

+ +

These are not part of ECMAScript standards (though the ES6 {{jsxref("Array.from()")}} can be used to achieve this). The following is a shim to allow its use in all browsers:

+ +
// Assumes Array extras already present (one may use polyfills for these as well)
+(function() {
+  'use strict';
+
+  var i,
+    // We could also build the array of methods with the following, but the
+    //   getOwnPropertyNames() method is non-shimable:
+    // Object.getOwnPropertyNames(Array).filter(function(methodName) {
+    //   return typeof Array[methodName] === 'function'
+    // });
+    methods = [
+      'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
+      'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
+      'forEach', 'map', 'reduce', 'reduceRight', 'filter',
+      'some', 'every', 'find', 'findIndex', 'entries', 'keys',
+      'values', 'copyWithin', 'includes'
+    ],
+    methodCount = methods.length,
+    assignArrayGeneric = function(methodName) {
+      if (!Array[methodName]) {
+        var method = Array.prototype[methodName];
+        if (typeof method === 'function') {
+          Array[methodName] = function() {
+            return method.call.apply(method, arguments);
+          };
+        }
+      }
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignArrayGeneric(methods[i]);
+  }
+}());
+
+ +

أمثلة

+ +

إنشاء مصفوفة

+ +

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

+ +
var msgArray = [];
+msgArray[0] = 'Hello';
+msgArray[99] = 'world';
+
+if (msgArray.length === 100) {
+  console.log('The length is 100.');
+}
+
+ +

إنشاء مصفوفة ذات بعدين

+ +

The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

+ +
var board = [
+  ['R','N','B','Q','K','B','N','R'],
+  ['P','P','P','P','P','P','P','P'],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  ['p','p','p','p','p','p','p','p'],
+  ['r','n','b','q','k','b','n','r'] ];
+
+console.log(board.join('\n') + '\n\n');
+
+// Move King's Pawn forward 2
+board[4][4] = board[6][4];
+board[6][4] = ' ';
+console.log(board.join('\n'));
+
+ +

هذه هي النتيجة (الخرج):

+ +
R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+p,p,p,p,p,p,p,p
+r,n,b,q,k,b,n,r
+
+R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , ,p, , ,
+ , , , , , , ,
+p,p,p,p, ,p,p,p
+r,n,b,q,k,b,n,r
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}New method added: {{jsxref("Array.prototype.includes()")}}
+ +

التوافق مع المتصفحات

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

إقرأ أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/isarray/index.html b/files/ar/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..f78eb1574d --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,146 @@ +--- +title: ()Array.isArray +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +
{{JSRef}}
+ +

()Array.isArray تفحص القيمة التي تم تمريرها هل هي {{jsxref("Array")}} أم ﻻ.

+ +

بنية الجملة

+ +
Array.isArray(value)
+ +

المعلمات

+ +
+
value
+
القيمة التي سيتم فحصها.
+
+ +

القيمة العائدة

+ +

تكون القيمة العائدة true إذا كانت {{jsxref("Array")}}؛ وتكون false إذا كانت غير ذلك.

+ +

الوصف

+ +

إذا كانت القيمة {{jsxref("Array")}}, true ستكون القيمة العائدة؛ غير ذلك ستكون false.

+ +

لمزيد من التفاصيل، راجع هذا المقال “Determining with absolute accuracy whether or not a JavaScript object is an array” .

+ +

أمثلة

+ +
//true جميع الأمثلة التالية ترجع
+Array.isArray([]);
+Array.isArray([1]);
+Array.isArray(new Array());
+//هي نفسها مصفوفة Array.prototype حقيقة معروفة أن
+Array.isArray(Array.prototype);
+
+//false جميع الأمثلة التالية ترجع
+Array.isArray();
+Array.isArray({});
+Array.isArray(null);
+Array.isArray(undefined);
+Array.isArray(17);
+Array.isArray('Array');
+Array.isArray(true);
+Array.isArray(false);
+Array.isArray({ __proto__: Array.prototype });
+
+ +

Polyfill

+ +

Running the following code before any other code will create Array.isArray() if it's not natively available.

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

المواصفات

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}}
+ +

التكامل مع المتصفحات

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

إقرأ أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/join/index.html b/files/ar/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..427509f1ec --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,143 @@ +--- +title: ()Array.prototype.join +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Prototype + - جافاسكربت + - دالة + - دمج Array + - دمج المصفوفات + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +
{{JSRef}}
+ +

دالة ()join تقوم بدمج جميع عناصر المصفوفة في نص واحد.

+ +
var a = ['Wind', 'Rain', 'Fire'];
+a.join();    // 'Wind,Rain,Fire'
+a.join('-'); // 'Wind-Rain-Fire'
+ +

صيغة الكتابة

+ +
str = arr.join([separator = ','])
+ +

المعاملات

+ +
+
separator
+
اختياري. يحدد النص الذي سيقوم بفصل عناصر المصفوفة عن بعضهم البعض. الـ separator سيتحول إلى جزء من النص الناتج. إذا لم يتم تمريره، سيتم الفصل بين عناصر المصفوفة بالـ comma. إذا كان الـseparator عبارة عن نص فارغ، سيتم ضم عناصر المصفوفة دون أي فاصل
+
+ +

القيمة العائدة

+ +

عناصر المصفوفة مضمومين في هيئة نص.

+ +

الوصف

+ +

تقوم بدمج عناصر المصفوفة في هيئة نص، إذا كان أحد هذه العناصر قيمة فارغة أو غير معرف سيتم تحويله إلى نص فارغ.

+ +

أمثلة

+ +

ضم عناصر المصفوفة بأربعة طرق مختلفة

+ +

المثال التالي يقوم بإنشاء مصفوفة a ، بها ثلاثة عناصر، ثم يقوم بضم هذه العناصر الثلاثة، ثم يقوم بضم هذه العناصر الثلاثة إلى نص واحد بأربعة طرق: استخدام الـ separator الإفتراضي، ثم باستخدام الـ comma والمسافة، ثم باستخدام علامة الجمع وأخيرا باستخدام نص فارغ.

+ +
var a = ['Wind', 'Rain', 'Fire'];
+var myVar1 = a.join();      // myVar1 إلى 'Wind,Rain,Fire' تسند
+var myVar2 = a.join(', ');  // myVar2 إلى 'Wind, Rain, Fire' تسند
+var myVar3 = a.join(' + '); // myVar3 إلى 'Wind + Rain + Fire' تسند
+var myVar4 = a.join('');    // myVar4 إلى 'WindRainFire' تسند
+
+ +

المواصفات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
الصفةالحالةتعليق
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}} 
+ +

التكامل مع المتصفحات

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

إقرأ أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/pop/index.html b/files/ar/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..247f45fc14 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,134 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +
{{JSRef}}
+   دالة pop() هي دالة تقوم بمسح أخر عنصر من المصفوفة وإرجاعه
+ +
 
+ +

Syntax

+ +
arr.pop()
+ +

قيمة الإرجاع

+ +

تعيد أخر عنصر من المصفوفة و تعيد {{jsxref("undefined")}}  في حال  كانت المصفوفة فارغة

+ +

وصف

+ +

 دالة POP هي دالة تقوم بمسح أخر عنصر من المصفوفة وإرجاع تلك القيمة إلى الطالب 

+ +

pop is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

+ +

 في حالة استدعائك لدالة POP على مصفوفة فارغة فسيتم إرجاع  {{jsxref("undefined")}} 

+ +

أمثلة

+ +

إزالة العنصر الأخير من المصفوفة

+ +

التعليمة البرمجية التالية : تقوم بإنشاء مصفوفة(myFish )   تحتوي على أربعة  عناصر ثم تقوم بمسح أخر عنصر   

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+
+console.log(myFish); // ['angel', 'clown', 'mandarin', 'sturgeon']
+
+var popped = myFish.pop();
+
+console.log(myFish); // ['angel', 'clown', 'mandarin' ]
+
+console.log(popped); // 'sturgeon'
+ +

مواصفات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مواصفاتالحالةتعليق
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/reverse/index.html b/files/ar/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..b179e52bc1 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,124 @@ +--- +title: ()Array.prototype.reverse +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +
{{JSRef}}
+ +

دالة الـ ()reverse تقوم بعكس ترتيبا عناصر المصفوفة مكانيا، بحيث يصبح العنصر الأول في المصفوفة في آخر المصفوفة، ويكون آخر عنصر فيها في أول المصفوفة.

+ +

صيغة الكتابة

+ +
arr.reverse()
+ +

القيمة العائدة

+ +

المصفوفة المعكوسة.

+ +

الوصف

+ +

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

+ +

أمثلة

+ +

عكس العناصر في مصفوفة

+ +

المثال التالي يقوم بإنشاء مصفوفة myArray تحتوي على ثلاثة عناصر، ثم يوم بعكس المصفوفة.

+ +
var myArray = ['one', 'two', 'three'];
+myArray.reverse();
+
+console.log(myArray) // ['three', 'two', 'one']
+
+ +

المواصفات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
المواصفةالحالةتعليق
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
+ +

التكامل مع المتصفحات

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

إقرأ أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/array/slice/index.html b/files/ar/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..c0e4bde2c2 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,151 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - المصفوفات + - جافا سكريبت +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +
{{JSRef}}
+ +

ال slice() method إرجاع نسخة ضئيلة من جزء من مصفوفة إلى object مصفوفة جديد تم تحديده من start إلى end (end غير مضمنة) بينما start و end تمثلان مؤشر العناصر في هذه المصفوفة. لن يتم تعديل المصفوفة الأصلية.

+ +
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
+ + + +

تركيب الجملة

+ +
arr.slice([start[, end]])
+
+ +

المعاملات

+ +
+
start {{optional_inline}}
+
مؤشر ذو أساس صفري يبدأ فيه الاستخراج.
+
يمكن استخدام مؤشر سلبي يشير إلى إزاحة من نهاية التسلسل. slice(-2) يستخرج آخر عنصرين في التسلسل.
+
إذا كانت start غير محددة, تبدأslice من المؤشر 0.
+
إذا كانت start is أكبر من نطاق فهرس التسلسل ، يتم إرجاع صفيف فارغ.
+
end {{optional_inline}}
+
مؤشر ذو أساس صفري قبل أن ينتهي الاستخراج. slice مستخرجات إلى ولا تشمل end. على سبيل المثال, slice(1,4) يستخرج العنصر الثاني من خلال العنصر الرابع (العناصر المفهرسة 1 و 2 و 3).
+
يمكن استخدام مؤشر سلبي يشير إلى إزاحة من نهاية التسلسل. slice(2,-1) يستخرج العنصر الثالث من خلال العنصر الثاني إلى الأخير في التسلسل.
+
إذا تم حذف end, slice مستخرجات من خلال نهاية التسلسل(arr.length).
+
اذا كانت end أكبر من طول التسلسل,  فإنslice تستخرج حتى نهاية التسلسل(arr.length).
+
+ +

القيمة العائدة

+ +

مصفوفة جديدة تحتوي على العناصر المستخرجة.

+ +

الوصف

+ +

slice لا تغير المصفوفة الأصلية. تقوم بإرجاع نسخة ضئيلة من العناصر من المصفوفة الأصلية. يتم نسخ عناصر الصفيف الأصلي في الصفيف الذي تم إرجاعه كما يلي:

+ + + +

إذا تمت إضافة عنصر جديد إلى أي مصفوفة ، فلن تتأثر المصفوفة الآخرى.

+ +

أمثلة

+ +

إعادة جزء من من مصفوفة موجودة

+ +
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+let citrus = fruits.slice(1, 3)
+
+// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contains ['Orange','Lemon']
+
+ +

باستخدام slice

+ +

في المثال التالي, تقومslice بإنشاء مصفوفة جديدة newCar, من myCar. كلاهما يتضمن إشارة إلى الobject myHonda. عندما يتغير لون myHonda إلى الأرجواني, تعكس كلا المصفوفتان التغيير.

+ +
// Using slice, create newCar from myCar.
+let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
+let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
+let newCar = myCar.slice(0, 2)
+
+// Display the values of myCar, newCar, and the color of myHonda
+//  referenced from both arrays.
+console.log('myCar = ' + JSON.stringify(myCar))
+console.log('newCar = ' + JSON.stringify(newCar))
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+// Change the color of myHonda.
+myHonda.color = 'purple'
+console.log('The new color of my Honda is ' + myHonda.color)
+
+// Display the color of myHonda referenced from both arrays.
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+ +

This script writes:

+ +
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
+         'cherry condition', 'purchased 1997']
+newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
+myCar[0].color = red
+newCar[0].color = red
+The new color of my Honda is purple
+myCar[0].color = purple
+newCar[0].color = purple
+
+ +

Array-like objects

+ +

slice method يمكن أيضًا استدعاؤها لتحويل  Array-like objects / مجموعات إلى مصفوفة جديدة. انت فقط {{jsxref("Function.prototype.bind", "bind")}} the method لل object. The {{jsxref("Functions/arguments", "arguments")}}داخل دالة هو مثال على 'array-like object'.

+ +
function list() {
+  return Array.prototype.slice.call(arguments)
+}
+
+let list1 = list(1, 2, 3) // [1, 2, 3]
+
+ +

البناء يمكن أن يتم ب {{jsxref("Function.prototype.call", "call()")}} method of {{jsxref("Function.prototype")}} ويمكن تقليلها باستخدام [].slice.call(arguments) بدلا منArray.prototype.slice.call.

+ +

على أي حال يمكن تبسيطها باستخدام {{jsxref("Function.prototype.bind", "bind")}}.

+ +
let unboundSlice = Array.prototype.slice
+let slice = Function.prototype.call.bind(unboundSlice)
+
+function list() {
+  return slice(arguments)
+}
+
+let list1 = list(1, 2, 3) // [1, 2, 3]
+ +

المواصفات

+ + + + + + + + + + + + +
مواصفات
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}
+ +

التوافق مع المتصفح

+ + + +

{{Compat("javascript.builtins.Array.slice")}}

+ +

انظر أيضا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/getdate/index.html b/files/ar/web/javascript/reference/global_objects/date/getdate/index.html new file mode 100644 index 0000000000..6a39d68196 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/getdate/index.html @@ -0,0 +1,85 @@ +--- +title: Date.prototype.getDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDate +tags: + - النموذج المبدئي + - تاريخ + - جافاسكربت + - طريقة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDate +--- +
{{JSRef}}
+ +

دالة getDate() تقوم بإرجاع يوم من تاريخ الشهر المحدد وفقاً للوقت المحلي.

+ +
{{EmbedInteractiveExample("pages/js/date-getdate.html")}}
+ + + +

بنية الجملة

+ +
dateObj.getDate()
+
+ +

القيمة العائدة

+ +

رقم صحيح ما بين 1 و31 يمثل يوم محدد من تاريخ الشهر المحدد وفقاً للوقت المحلي.

+ +

أمثلة

+ +

استخدام getDate()

+ +

البيان الثاني قام بتعيين قيمة المتغير day، علي أساس قيمة تاريخ المتغير Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var day = Xmas95.getDate();
+
+console.log(day); // 25
+
+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.getDate")}}

+ +

اقرأ أيضًا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/index.html b/files/ar/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..efaa40ce31 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,261 @@ +--- +title: Date | التاريخ +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Date + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

+ +

البنيه

+ +
new Date();
+new Date(value);
+new Date(dateString);
+new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
+
+ +
+

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the {{jsxref("Operators/new", "new")}} operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

+
+ +

Parameters

+ +
+

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

+
+ +
+

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) with the same arguments.

+
+ +
+
value
+
Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).
+
dateString
+
String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601). +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+
+
year
+
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the {{anch("Example:_Two_digit_years_map_to_1900_-_1999", "example below")}}.
+
month
+
Integer value representing the month, beginning with 0 for January to 11 for December.
+
day
+
Optional. Integer value representing the day of the month.
+
hour
+
Optional. Integer value representing the hour of the day.
+
minute
+
Optional. Integer value representing the minute segment of a time.
+
second
+
Optional. Integer value representing the second segment of a time.
+
millisecond
+
Optional. Integer value representing the millisecond segment of a time.
+
+ +

Description

+ + + +

Properties

+ +
+
{{jsxref("Date.prototype")}}
+
Allows the addition of properties to a JavaScript Date object.
+
Date.length
+
The value of Date.length is 7. This is the number of arguments handled by the constructor.
+
+ +

Methods

+ +
+
{{jsxref("Date.now()")}}
+
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
+
{{jsxref("Date.parse()")}}
+
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. +
+

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

+
+
+
{{jsxref("Date.UTC()")}}
+
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC.
+
+ +

JavaScript Date instances

+ +

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

+ +

Date.prototype Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
+ +

Examples

+ +

Several ways to create a Date object

+ +

The following examples show several ways to create JavaScript dates:

+ +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+ +
var today = new Date();
+var birthday = new Date('December 17, 1995 03:24:00');
+var birthday = new Date('1995-12-17T03:24:00');
+var birthday = new Date(1995, 11, 17);
+var birthday = new Date(1995, 11, 17, 3, 24, 0);
+
+ +

Two digit years map to 1900 - 1999

+ +

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

+ +
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+// Deprecated method, 98 maps to 1998 here as well
+date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
+
+ +

Calculating elapsed time

+ +

The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.

+ +

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

+ +
// using Date objects
+var start = Date.now();
+
+// the event to time goes here:
+doSomethingForALongTime();
+var end = Date.now();
+var elapsed = end - start; // elapsed time in milliseconds
+
+ +
// using built-in methods
+var start = new Date();
+
+// the event to time goes here:
+doSomethingForALongTime();
+var end = new Date();
+var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
+
+ +
// to test a function and get back its return
+function printElapsedTime(fTest) {
+  var nStartTime = Date.now(),
+      vReturn = fTest(),
+      nEndTime = Date.now();
+
+  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
+  return vReturn;
+}
+
+yourFunctionReturn = printElapsedTime(yourFunction);
+
+ +
+

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Some browsers can have issues when parsing dates: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

+ +

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

diff --git a/files/ar/web/javascript/reference/global_objects/date/now/index.html b/files/ar/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..ff6379db60 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,80 @@ +--- +title: Date.now() | دالة الوقت الآن +slug: Web/JavaScript/Reference/Global_Objects/Date/now +tags: + - Date + - التاريخ + - الوقت + - جافاسكربت + - دالة + - دليل + - طريقة بديلة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
{{JSRef}}
+ +

تقوم دالة  Date.now() بعرض عدد الثواني التي مضت منذ بداية احتساب الوقت بطريقة Timestamp وهو الأول من يناير عام 1970 الساعة الثانية عشر منتصف الليل تمامًا (First of January 1970 00:00:00)  بتوقيت UTC.

+ +

بنية الجملة

+ +
var timeInMs = Date.now();
+ +

القيمة الراجعة

+ +

القيمة الراجعة من هذه الدالة ستكون عبارة عن رقم  {{jsxref("Number")}}، هذا الرقم يشير إلى عدد الثواني التي انقضت منذ بداية احتساب الوقت بطريقة TimeStamp بالأنظمة التي تستند إلى UNIX.

+ +

الوصف

+ +

لإن دالة  now() تقوم بإرجاع قيمة ثابتة من الوقت {{jsxref("Date")}} فيجب عليك استخدامها بهذا الشكل   Date.now() .

+ +

طريقة احتياطية (Polyfill)

+ +

تم اعتماد هذه الدالة  في  إصدار ECMA-262 5th المحركات التي لم يتم تحديثها لتدعم هذه الدالة يمكنها أن تحاكي دالة Date.now() عبر استخدام هذه الشيفرة البرمجية، هذه الشيفرة ستسمح للمتصفحات بأن تحاكي وظيفة هذه الدالة في حالة عدم دعمها لها :

+ +
if (!Date.now) { // إذا لم تكن الدالة موجودة
+  Date.now = function now() { // قم بإنشاء الدالة
+    return new Date().getTime(); // واربطها بالوقت الحالي
+  };
+}
+
+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + +
الخاصيةالحالةتعليقات
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.now")}}

+ +

اقرأ أيضًا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/parse/index.html b/files/ar/web/javascript/reference/global_objects/date/parse/index.html new file mode 100644 index 0000000000..133b751cd6 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/parse/index.html @@ -0,0 +1,182 @@ +--- +title: Date.parse() | دالة تحليل الوقت +slug: Web/JavaScript/Reference/Global_Objects/Date/parse +tags: + - Date + - التاريخ + - جافاسكربت + - طريقة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/parse +--- +
{{JSRef}}
+ +

تقوم دالة Date.parse() بتوزيع سلسلة من التاريخ، وإرجاع قيمتها إلي مللي ثانية من بداية تاريخ (1 يناير, 1970, 00:00:00 UTC) إلي التاريخ المحدد داخل الأقواس مثل Date.parse("التاريخ") أو NaN (ليس رقم) إذا كانت السلسلة غير معترف بها (غير صحيحة)، أو في بعض الحالات التي يكون فيها قيم التاريخ غير شرعية (مكتوبة بشكل خاطيء). علي سبيل المثال (2015-02-31).

+ +

It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).

+ +
{{EmbedInteractiveExample("pages/js/date-parse.html")}}
+ + + +

بنية الجملة

+ +

استدعاء مباشر:

+ +
Date.parse(dateString)
+ +

استدعاء ضمني:

+ +
new Date(dateString)
+ +

المعاملات

+ +
+
dateString
+
النص يمثل RFC2822 أو (a variant of) تاريخ ISO 8601 (قد يتم استخدام تنسيقات أخري، ولكن ربما قد تكون النتائج غير متوقعة).
+
+ +

القيمة الراجعة

+ +

A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, {{jsxref("NaN")}} is returned.

+ +

الوصف

+ +

تقوم دالة parse() بأخذ سلسلة التاريخ مثل ("Des 25, 1995") وتقوم بإرجاع القيمة إلي المللي ثانية منذ بداية احتساب الوقت وهو الأول من يناير عام 1970 الساعة الثانية عشر منتصف الليل تماماً (First of January 1970 00:00:00)  بتوقيت UTC، حتي الوقت التي قمت بتحديده. وهذه الدالة مفيدة لتعيين قيمة التاريخ استناداً الي قيمة السلسلة، علي سبيل المثال الدمج مع طريقة  {{jsxref("Date.prototype.setTime()", "setTime()")}} و {{jsxref("Global_Objects/Date", "Date")}} .

+ +

Given a string representing a time, parse() returns the time value. It accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g. "Mon, 25 Dec 1995 13:30:00 GMT". It understands the continental US time zone abbreviations, but for general use, use a time zone offset, for example, "Mon, 25 Dec 1995 13:30:00 +0430" (4 hours, 30 minutes east of the Greenwich meridian).

+ +

GMT and UTC are considered equivalent. The local time zone is used to interpret arguments in RFC2822 Section 3.3 format that do not contain time zone information.

+ +

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

+ +

ECMAScript 5 دعم تنسيق ISO-8601

+ +

The date time string may be in a simplified ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed. Where the string is ISO 8601 date only, the UTC time zone is used to interpret arguments. If the string is date and time in ISO 8601 format, it will be treated as local.

+ +

While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or NaN.

+ +

Because parse() is a static method of {{jsxref("Date")}}, it is called as Date.parse() rather than as a method of a {{jsxref("Date")}} instance.

+ +

الاختلافات في المنطقة الزمنية المفترضة

+ +

Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore {{jsxref("Date")}} objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.

+ +

Fall-back to implementation-specific date formats

+ +

The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return {{jsxref("NaN")}}.

+ +

However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in {{jsxref("NaN")}}, depending on the browser and values provided, e.g.:

+ +
// سلسلة ليست أيزو مع قيم تاريخ صالحة
+new Date('23/25/2014');
+
+ +

will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return {{jsxref("NaN")}} in all browsers compliant with ES5 and later:

+ +
// سلسلة أيزو مع قيمة غير صالحة
+new Date('2014-25-23').toISOString();
+// يُعيد "RangeError: invalid date" في جميع المتصفحات المتوافقة مع es5
+
+ +

SpiderMonkey's implementation-specific heuristic can be found in jsdate.cpp. The string "10 06 2014" is an example of a non–conforming ISO format and thus falls back to a custom routine. See also this rough outline on how the parsing works.

+ +
new Date('10 06 2014');
+
+ +

will be treated as a local date of 6 October, 2014 and not 10 June, 2014. Other examples:

+ +
new Date('foo-bar 2014').toString();
+// يُعيد: "Invalid Date" *تاريخ غير صالح*
+
+Date.parse('foo-bar 2014');
+// يُعيد: NaN *ليس رقم*
+
+ +

أمثلة

+ +

استخدام Date.parse()

+ +

إذا كان IPOdate هو كائن {{jsxref("Date")}} موجود، فيمكن تعيينه إلي 9 أغسطس، 1995 (بالتوقيت المحلي) كما يلي:

+ +
IPOdate.setTime(Date.parse('Aug 9, 1995'));
+ +

بعض الأمثلة الأخرى على تحليل سلاسل التاريخ غير القياسية:

+ +
Date.parse('Aug 9, 1995');
+ +

يٌعيد 807937200000 في المنطقة الزمنية GMT-0300، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.

+ +
Date.parse('Wed, 09 Aug 1995 00:00:00 GMT');
+ +

يٌعيد 807926400000 بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).

+ +
Date.parse('Wed, 09 Aug 1995 00:00:00');
+
+ +

يٌعيد 807937200000 في المنطقة الزمنية GMT-0300، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT');
+
+ +

يٌعيد 0 بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00');
+
+ +

يٌعيد 14400000 في المنطقة الزمنية GMT-0400، ويٌعيد قيم أخري في المناطق الزمنية الأخري، حيث أن السلسلة لا تحدد المناطق الزمنية وهي ليست بتنسيق ISO، وبالتالي فإن المنطقة الزمنية الافتراضية بدون تنسيق ISO هي المنطقة الزمنية المحلية الخاصة بالدولة الموجود بها. وتختلف من دولة إلي آخري.

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400');
+
+ +

يٌعيد 14400000 بغض النظر عن المنطقة الزمنية المحلية مثل GMT (UTC).

+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.4.2', 'Date.parse')}}{{Spec2('ES5.1')}}Simplified ISO 8601 format added.
{{SpecName('ES6', '#sec-date.parse', 'Date.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.parse', 'Date.parse')}}{{Spec2('ESDraft')}} 
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.parse")}}

+ +

ملاحظات التوافق

+ + + +

اقرأ أيضًا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/setdate/index.html b/files/ar/web/javascript/reference/global_objects/date/setdate/index.html new file mode 100644 index 0000000000..ca5d89a63e --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/setdate/index.html @@ -0,0 +1,95 @@ +--- +title: Date.prototype.setDate() | دالة تعيين التاريخ +slug: Web/JavaScript/Reference/Global_Objects/Date/setDate +tags: + - التاريخ + - النموذج المبدئي + - جافاسكربت + - طريقة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setDate +--- +
{{JSRef}}
+ +

دالة setDate() تقوم بتعين يوم من الـ {{jsxref("Date")}} المحدد نسبه إلي الشهر المحدد.

+ +
{{EmbedInteractiveExample("pages/js/date-setdate.html")}}
+ + + +

بنية الجملة

+ +
dateObj.setDate(dayValue [رقم اليوم])
+ +

المعاملات (Parameters)

+ +
+
dayValue
+
يجب أن يكون عدد صحيح يمثل يوم من الشهر. علي سبيل المثال setDate(15) .
+
+ +

القيمة العائدة

+ +

عدد المللي ثانية بين تاريخ 1 يناير 1970 00:00:00 UTC والتاريخ المحدد (يتغير الـ {{jsxref("Date")}} أيضا بتغير المكان [المنطقة الزمنية]).

+ +

الوصف

+ +

إذا كان dayValue [رقم اليوم] خارج نطاق قيم الشهر المحدد لهذا التاريخ، فأن دالة setDate() ستقوم بتحديد الـ {{jsxref("Date")}} [اليوم] وفقاً لذلك. علي سبيل المثال، إذا تم تحديد dayValue [رقم اليوم] إلي 0 فسيتم تعيين التاريخ إلي أخر يوم في الشهر السابق.

+ +

أمثلة

+ +

استخدام setDate()

+ +
var theBigDay = new Date(1962, 6, 7); // 1962-07-07
+theBigDay.setDate(24);  // 1962-07-24
+theBigDay.setDate(32);  // 1962-08-01
+theBigDay.setDate(22);  // 1962-08-22
+theBigDay.setDate(0); // 1962-06-30
+theBigDay.setDate(98); // 1962-10-06
+theBigDay.setDate(-50); // 1962-08-09
+
+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.36', 'Date.prototype.setDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}{{Spec2('ESDraft')}} 
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.setDate")}}

+ +

اقرأ أيضًا

+ + diff --git a/files/ar/web/javascript/reference/global_objects/date/utc/index.html b/files/ar/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..2d1400af0e --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,133 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Reference/Global_Objects/Date/UTC +tags: + - تاريخ + - جافاسكربت + - طريقة + - مرجع +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +
{{JSRef}}
+ +

دالة Date.UTC() تقبل نفس المُعاملات parameters علي الرغم من طول تكوين المنشيء، ويٌعيد التاريخ إلي المللي ثانية من بداية تاريخ 1 يناير, 1970, 00:00:00, التوقيت العالمي.

+ +
{{EmbedInteractiveExample("pages/js/date-utc.html")}}
+ + + +

بنية الجملة

+ +
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
+ +

المعاملات (Parameters)

+ +
+
year
+
سنة كاملة.
+
month
+
رقم صحيح ما بين 0 و11 يمثل الشهر.
+
day
+
اختياري. رقم صحيح ما بين 1 و31 يمثل يوم من الشهر.
+
hour
+
اختياري. رقم صحيح ما بين 0 و23 يمثل الساعات.
+
minute
+
اختياري. رقم صحيح ما بين 0 و59 يمثل الدقائق.
+
second
+
اختياري. رقم صحيح ما بين 0 و59 يمثل الثواني.
+
millisecond
+
اختياري. رقم صحيح ما بين 0 و999 يمثل الميلي ثانية.
+
+ +

القيمة العائدة

+ +

رقم يمثل عدد المللي ثانية في التاريخ المحدد منذ 1 يناير, 1970, 00:00:00، التوقيت العالمي.

+ +

الوصف

+ +

تقوم دالة UTC() بأخذ معاملات (parameters) التاريخ المحددة بفاصلة ثم تُعيدها إلي مللي ثانية بين 1 يناير 1970، 00:00:00 التوقيت العالمي، والوقت الذي حددته.

+ +

يجب عليك تحديد السنة كاملة؛ علي سبيل المثال, 1998. إذا كانت السنة محددة ما بين عام 0 و99، تقوم هذه الطريقة بتحويل السنه إلي سنه في القرن العشرين (1900 + سنة)؛ علي سبيل المثال، إذا حددت 95، فسيتم أستخدام 1995.

+ +

تختلف طريقة UTC() عن منشيء التاريخ بطريقتين.

+ + + +

If a parameter you specify is outside of the expected range, the UTC() method updates the other parameters to allow for your number. For example, if you use 15 for month, the year will be incremented by 1 (year + 1), and 3 will be used for the month.

+ +

Because UTC() is a static method of {{jsxref("Date")}}, you always use it as Date.UTC(), rather than as a method of a {{jsxref("Date")}} object you created.

+ +

أمثلة

+ +

استخدام Date.UTC()

+ +

في المثال التالي يقوم بإنشاء التاريخ بإستخدام UTC بدلاً من التوقيت المحلي:

+ +
var utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
+
+ +

الخصائص

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

دعم المتصفحات

+ + + +

{{Compat("javascript.builtins.Date.UTC")}}

+ +

ملاحظات التوافق

+ +

Date.UTC with fewer than two arguments

+ +

When providing less than two arguments to Date.UTC, {{jsxref("NaN")}} is returned. This behavior is specified in ECMAScript 2017. Engines who weren't supporting this behavior, have been updated (see {{bug(1050755)}}, ecma-262 #642).

+ +
Date.UTC();
+Date.UTC(1);
+
+// Safari: NaN
+// Chrome/Opera/V8: NaN
+
+// Firefox <54: non-NaN
+// Firefox 54+: NaN
+
+// IE: non-NaN
+// Edge: NaN
+
+ +

اقرأ أيضاً

+ + diff --git a/files/ar/web/javascript/reference/global_objects/function/call/index.html b/files/ar/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..f3c83f04ac --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,219 @@ +--- +title: ()Function.prototype.call +slug: Web/JavaScript/Reference/Global_Objects/Function/call +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +
{{JSRef}}
+ +
+

تُستدعَى الوظيفة ()call على دالة، أول argument لهذه الوظيفة هو قيمة this الخاصة بالدالة، وال arguments المتبقية (إن وُجدت)، هي  arguments الدالة.

+ +
+

ملاحظة :   صيغة هذه الوظيفة مماثلة تقريبًا  للصيغة الخاصة بـ {{jsxref("Function.prototype.apply", "apply")}} الفرق الوحيد هو ان  ()call تاخذ قائمة من ال arguments  محددة بشكل فردي فيما تاخذ ()apply مصفوفة واحدة من ال arguments.

+
+ +
{{EmbedInteractiveExample("pages/js/function-call.html")}}
+ + + +

صيغة الوظيفة call

+ +
function.call(thisArg, arg1, arg2, ...)
+ +

Parameters

+ +
+
thisArg
+
اختياري. وهو قيمة this المتوفرة في استدعاء الدالة function. لاحظ أن this قد لا تكون القيمة الفعلية التي تراها الوظيفة: اذا كانت هذه الوظيفة دالة في  {{jsxref("Strict_mode", "non-strict mode", "", 1)}} سيتم استبدال  {{jsxref("Global_Objects/null", "null")}} و {{jsxref("Global_Objects/undefined", "undefined")}} بالكائن العام والقيم الاولية ستحول الى كائنات.  
+
...,arg1, arg2
+
 arguments الدالة function.
+
+ +

Return value

+ +

تُرجع نتيجة استدعاء الدالة مع قيمة  this المحددة و ال arguments.

+ +

وصف

+ +

تسمح الوظيفة ()call لدالة او وظيفة خاصة بكائن واحد بان يتم استدعاؤها وتعيينها من قبل كائن مختلف.

+ +

تمنح الوظيفة ()call قيمة this الجديدة الى الدالة/الوظيفة. مع الـ call  يمكنك كتابة الوظيفة مرة واحدة ومن ثم تقوم بتوريثها لكائن آخر دون الحاجة إلى إعادة كتابة الوظيفة للكائن الجديد.

+ +

تحليل الجزء الغامض في الوظيفة ()call

+ +

نظرا لعدم وجود شرح كاف حول هذه الجزئية فقد ارتايت ان اظيف هذه الفقرة التوضيحية لعلها تزيح بعض الغموض عن قيمة ال this التي تمثل ال argument الاول لهذه الوظيفة.

+ +

اذا نظرنا بتمعن في هذا الجزء من داخل الوظيفة call. سنجد ان thisArg ستساوي الكائن العام في حالة undefined او null، والا ستساوي ناتج الكائن Object، تساوي thisArg كائنا في كلتا الحالتين. وعليه فقد اصبحت كائنا، اذن فمن الطبيعي ان تمتلك خصائص. تم تحديد الخاصية _callTemp_ قيمتها this و this تمثل الدالة التي ستستدعى عليها الوظيفة call. واخيرا يتم تنفيذ هذه الدالة:

+ +
Function.prototype.call_like = function( thisArg, args ){
+    thisArg = ( thisArg === undefined || thisArg === null ) ? window : Object( thisArg );
+    thisArg._callTemp_ = this;
+    thisArg._callTemp_();
+}
+ +

في حالة عدم وجود thisArg ستتصرف الدالة fn بشكل طبيعي و this ستساوي الكائن العام:

+ +
var fn = function () {
+    console.log( this ); // [object Window]
+}
+fn.call_like();
+
+
+ +

في حالة وجود thisArg بقيمة اولية ك undefined او null ف this ستساوي ايضا الكائن العام، خلاف ذالك سيتم تمرير قيمتها الى الكائن ()Object، اذا كانت هذه القيمة من القيم الاولية-primitive value سيقوم الكائن بتحويلها الى الكائن المناسب لها، واما اذا كانت هذه القيمة كائنا فلا حاجة لتحويلها و this ستساوي كائنا.

+ +

وهذا يفسر كيف قام الكائن Object بتحويل القيمة الاولية "Youssef belmeskine" الى الكائن String:   

+ +
var fn = function () {
+    console.log( this ); // "Youssef belmeskine"
+    console.log( this === "Youssef belmeskine" ); // false
+    console.log( String(this) === "Youssef belmeskine" ); // true
+}
+fn.call_like( "Youssef belmeskine" );
+
+
+ +

من المهم دائما ذكر المصدر:

+ +
+

بالنسبة لى شخصيا لم اتمكن من فهم هذه الوظيفة وشقيقتها apply بشكل واضح الا عندما قمت بالاطلاع على الكود الداخلى لها. قمت باستخدام هذا الجزء من الكود لتوضيح الفكرة فقط. ستجد ال Polyfill كاملا في هذا الموقع hexmen.com.

+
+ +

أمثلة

+ +

استخدام ال call لِسَلسَلة منشئات الكائن

+ +

تستطيع إستخدام call  لعمل تسلسل لمنشئات-constructors الكائن، وذلك على غرار جافا. في المثال التالي، تم تحديد منشئ الكائن Product مع اثنين من البارامترات name و price. والدالتات Food و Toy  تستدعيان  Product  ممرر لها this و name و price. تقوم Product بتهيئة الخاصيتان name و price فيما تقوم كلا الدالتان المتخصصتان بتحديد ال category.

+ +
function Product(name, price) {
+  this.name = name;
+  this.price = price;
+}
+
+function Food(name, price) {
+  Product.call(this, name, price);
+  this.category = 'food';
+}
+
+function Toy(name, price) {
+  Product.call(this, name, price);
+  this.category = 'toy';
+}
+
+var cheese = new Food('feta', 5);
+var fun = new Toy('robot', 40);
+
+ +

إستخدام ال call لإستدعاء الدالة المجهولة الاسم-anonymous function 

+ +

في هذا المثال قمنا بانشاء الدالة المجهولة واستخدمنا call  لإستدعاءها على كل كائن في المصفوفة. الغرض الرئيسي من الدالة المجهولة هو إضافة الدالة print الى كل كائن،  والتي ستكون قادرة على طباعة الفهرس الصحيح لكائنات المصفوفة. تمرير كائن على شكل قيمة this ليس ضروريًا، ولكن تم إنجازه لغرض توضيحي.

+ +
var animals = [
+  { species: 'Lion', name: 'King' },
+  { species: 'Whale', name: 'Fail' }
+];
+
+for (var i = 0; i < animals.length; i++) {
+  (function(i) {
+    this.print = function() {
+      console.log('#' + i + ' ' + this.species
+                  + ': ' + this.name);
+    }
+    this.print();
+  }).call(animals[i], i);
+}
+
+ +

استخدام call لاستدعاء دالة وتحديد السياق-context ل   this

+ +

في المثال أدناه، عندما سنقوم باستدعاء greet سترتبط قيمة this  بالكائن obj.

+ +
function greet() {
+  var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
+  console.log(reply);
+}
+
+var obj = {
+  animal: 'cats', sleepDuration: '12 and 16 hours'
+};
+
+greet.call(obj);  // cats typically sleep between 12 and 16 hours
+
+ +

إستخدام الـcall لاستدعاء دالة وبدون تحديد البرامتر الاول

+ +

في المثال أدناه ،قمنا باستدعاء الدالة display من دون تمرير البرامتر الاول. إذا لم يتم تمرير قيمة this في البرامتر الاول فسترتبط بالكائن العام-global object.

+
+ +
var sData = 'Wisen';
+
+function display(){
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call();  // sData value is Wisen
+
+ +
+

تذكر ان قيمة this ستكون  ب undefined في الوضع الصارم. انظر ادناه:

+
+ +
'use strict';
+
+var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call(); // Cannot read the property of 'sData' of undefined
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.4', 'Function.prototype.call')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Function.call")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/function/index.html b/files/ar/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..878d8776b3 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,183 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues similar to {{jsxref("eval")}}. However, unlike eval, the Function constructor allows executing code in the global scope, prompting better programming habits and allower for more efficient code minification.

+ +
{{EmbedInteractiveExample("pages/js/function-constructor.html")}}
+ + + +

Every JavaScript function is actually a Function object. This can be seen with the code (function(){}).constructor === Function which returns true.

+ +

Syntax

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parameters

+ +
+
arg1, arg2, ... argN
+
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Description

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. However, getting rid of the new operator allows for a smaller minified code size (4 bytes smaller), so it is best to not use new with Function.

+ +

Properties and Methods of Function

+ +

The global Function object has no methods or properties of its own. However, since it is a function itself, it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

+ +

Function prototype object

+ +

Properties

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
+ +

Methods

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function instances

+ +

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// Example can be run directly in your JavaScript console
+
+// Create a function that takes two arguments and returns the sum of those arguments
+var adder = new Function('a', 'b', 'return a + b');
+
+// Call the function
+adder(2, 6);
+// > 8
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

Difference between Function constructor and function declaration

+ +

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+ +
var x = 10;
+
+function createFunction1() {
+    var x = 20;
+    return new Function('return x;'); // this |x| refers global |x|
+}
+
+function createFunction2() {
+    var x = 20;
+    function f() {
+        return x; // this |x| refers local |x| above
+    }
+    return f;
+}
+
+var f1 = createFunction1();
+console.log(f1());          // 10
+var f2 = createFunction2();
+console.log(f2());          // 20
+
+ +

The "proper" way to execute external code with Function (for maximum minifyability).

+ +
function makeFunction(code){
+    return Function('"use strict";return ' + code)();
+}
+var add = makeFunction(
+  "" + function(a, b, c){ return a + b + c } // move this to a separate file in the production release
+);
+console.log( add(1, 2, 3) ); // will log six
+ +

Please note that the above code by itself is completely impractical. You should never abuse Function like that. Instead, the above code is meant only to be a simplified example of something like a module loader where there is a base script, then there are hundreads of big optionally loaded modules. Then, instead of the user waiting while they all download, the clients computer only downloads modules as needed so the page loads super fast. Also, it is reccomended that when evaluating many functions, the functions are evaluated together in bulk instead of separatly.

+ +
function bulkMakeFunctions(){
+    var str = "", i = 1, Len = arguments.length;
+    if (Len) {
+        str = arguments[0];
+        while (i !== Len) str += "," + arguments[i], ++i;
+    }
+    return Function('"use strict";return[' + str + ']')();
+}
+const [
+    add,                        sub,                        mul,                        div
+] = bulkMakeFunctions(
+    "function(a,b){return a+b}","function(a,b){return a-b}","function(a,b){return a*b}","function(a,b){return a/b}"
+);
+console.log(sub(add(mul(4,3), div(225,5)), 7))
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Function")}}

+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/index.html b/files/ar/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..0e46a82c09 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/index.html @@ -0,0 +1,126 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
+ {{jsSidebar("Objects")}}
+

Summary

+

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

+
+

The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, global objects refer to objects in the global scope (but only if ECMAScript 5 strict mode is not used! Otherwise it returns undefined). The global object itself can be accessed by the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope consists of the properties of the global object (including inherited properties, if any).

+

Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview.

+

Standard objects (by category)

+

Value properties

+

Global properties returning a simple value.

+ +

Function properties

+

Global functions returning the result of a specific routine.

+ +

Fundamental objects

+

General language objects, functions and errors.

+ +

Numbers and dates

+

Objects dealing with numbers, dates and mathematical calculations.

+ +

Text processing

+

Objects for manipulating texts.

+ +

Indexed collections

+

Collections ordered by an index. Array-type objects.

+ +

Keyed collections

+

Collections of objects as keys. Elements iterable in insertion order.

+ +

Structured data

+

Data buffers and JavaScript Object Notation.

+ +

Control abstraction objects

+ +

Reflection

+ +

Internationalization

+

Additions to the ECMAScript core for language-sensitive functionalities.

+ +

Other

+ +
+

 

diff --git a/files/ar/web/javascript/reference/global_objects/json/index.html b/files/ar/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..60305cbd07 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,215 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - NeedsTranslation + - Object + - Reference + - TopicStub + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef("Global_Objects", "JSON")}}
+ +

Summary

+

The JSON object contains methods for parsing JavaScript Object Notation ({{glossary("JSON")}}) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.

+ +

Description

+ +

JavaScript Object Notation

+

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and {{jsxref("null")}}. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON, and some JSON is not JavaScript. See also JSON: The JavaScript subset that isn't.

+ + + + + + + + + + + + + + + + + + + + + + +
JavaScript and JSON differences
JavaScript typeJSON differences
Objects and ArraysProperty names must be double-quoted strings; trailing commas are forbidden.
NumbersLeading zeros are prohibited; a decimal point must be followed by at least one digit.
Strings +

Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted. See the following example where {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:

+
+var code = '"\u2028\u2029"';
+JSON.parse(code); // works fine
+eval(code); // fails
+
+
+

The full JSON syntax is as follows:

+
JSON = null
+    or true or false
+    or JSONNumber
+    or JSONString
+    or JSONObject
+    or JSONArray
+
+JSONNumber = - PositiveNumber
+          or PositiveNumber
+PositiveNumber = DecimalNumber
+              or DecimalNumber . Digits
+              or DecimalNumber . Digits ExponentPart
+              or DecimalNumber ExponentPart
+DecimalNumber = 0
+             or OneToNine Digits
+ExponentPart = e Exponent
+            or E Exponent
+Exponent = Digits
+        or + Digits
+        or - Digits
+Digits = Digit
+      or Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          or " StringCharacters "
+StringCharacters = StringCharacter
+                or StringCharacters StringCharacter
+StringCharacter = any character
+                  except " or \ or U+0000 through U+001F
+               or EscapeSequence
+EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
+              or \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 through 9
+        or A through F
+        or a through f
+
+JSONObject = { }
+          or { Members }
+Members = JSONString : JSON
+       or Members , JSONString : JSON
+
+JSONArray = [ ]
+         or [ ArrayElements ]
+ArrayElements = JSON
+             or ArrayElements , JSON
+
+

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

+ +

Methods

+
+
{{jsxref("JSON.parse()")}}
+
Parse a string as JSON, optionally transform the produced value and its properties, and return the value.
+
{{jsxref("JSON.stringify()")}}
+
Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
+
+ +

Polyfill

+

The JSON object is not supported in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of JSON object in implementations which do not natively support it (like Internet Explorer 6).

+

The following algorithm is an imitation of the native JSON object:

+
if (!window.JSON) {
+  window.JSON = {
+    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
+    stringify: function(vContent) {
+      if (vContent instanceof Object) {
+        var sOutput = '';
+        if (vContent.constructor === Array) {
+          for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + ',', nId++);
+          return '[' + sOutput.substr(0, sOutput.length - 1) + ']';
+        }
+        if (vContent.toString !== Object.prototype.toString) {
+          return '"' + vContent.toString().replace(/"/g, '\\$&') + '"';
+        }
+        for (var sProp in vContent) {
+          sOutput += '"' + sProp.replace(/"/g, '\\$&') + '":' + this.stringify(vContent[sProp]) + ',';
+        }
+        return '{' + sOutput.substr(0, sOutput.length - 1) + '}';
+     }
+     return typeof vContent === 'string' ? '"' + vContent.replace(/"/g, '\\$&') + '"' : String(vContent);
+    }
+  };
+}
+
+

More complex well-known polyfills for the JSON object are JSON2 and JSON3.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+
{{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
+
+
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+

Based on Kangax's compat table.

+ +

See also

+ diff --git a/files/ar/web/javascript/reference/global_objects/map/index.html b/files/ar/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..ba5bc93804 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,358 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +
{{JSRef}}
+ +

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and {{glossary("Primitive", "primitive values")}}) may be used as either a key or a value.

+ +

Description

+ +

A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of [key, value] for each iteration.

+ +

Key equality

+ + + +

Objects vs. Maps

+ +

{{jsxref("Object")}} is similar to Map—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), Objects have been used as Maps historically.

+ +

However, there are important differences that make Map preferable in certain cases:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MapObject
Accidental KeysA Map does not contain any keys by default. It only contains what is explicitly put into it. +

An Object has a prototype, so it contains default keys that could collide with your own keys if you're not careful.

+ +
+

Note: As of ES5, this can be bypassed by using {{jsxref("Object.create", "Object.create(null)")}}, but this is seldom done.

+
+
Key TypesA Map's keys can be any value (including functions, objects, or any primitive).The keys of an Object must be either a {{jsxref("String")}} or a {{jsxref("Symbol")}}.
Key Order +

The keys in Map are ordered. Thus, when iterating over it, a Map object returns keys in order of insertion.

+
+

The keys of an Object are not ordered.

+ +
+

Note: Since ECMAScript 2015, objects do preserve creation order for string and Symbol keys. In JavaScript engines that comply with the ECMAScript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion.

+
+
SizeThe number of items in a Map is easily retrieved from its {{jsxref("Map.prototype.size", "size")}} property.The number of items in an Object must be determined manually.
IterationA Map is an iterable, so it can be directly iterated.Iterating over an Object requires obtaining its keys in some fashion and iterating over them.
Performance +

Performs better in scenarios involving frequent additions and removals of key-value pairs.

+
+

Not optimized for frequent additions and removals of key-value pairs.

+
+ +

Setting object properties

+ +

Setting Object properties works for Map objects as well, and can cause considerable confusion.

+ +

Therefore, this appears to work in a way:

+ +
let wrongMap = new Map()
+wrongMap['bla'] = 'blaa'
+wrongMap['bla2'] = 'blaaa2'
+
+console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }
+
+ +

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of 'bla' is not stored in the Map for queries. Othere operations on the data fail:

+ +
wrongMap.has('bla')    // false
+wrongMap.delete('bla') // false
+console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }
+ +

The correct usage for storing data in the Map is through the set(key, value) method.

+ +
let contacts = new Map()
+contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
+contacts.has('Jessie') // true
+contacts.get('Hilary') // undefined
+contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
+contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
+contacts.delete('Raymond') // false
+contacts.delete('Jessie') // true
+console.log(contacts.size) // 1
+
+
+ +

Constructor

+ +
+
{{jsxref("Map/Map", "Map()")}}
+
Creates a new Map object.
+
+ +

Static properties

+ +
+
{{jsxref("Map.@@species", "get Map[@@species]")}}
+
The constructor function that is used to create derived objects.
+
+ +

Instance properties

+ +
+
{{jsxref("Map.prototype.size")}}
+
Returns the number of key/value pairs in the Map object.
+
+ +

Instance methods

+ +
+
{{jsxref("Map.prototype.clear()")}}
+
Removes all key-value pairs from the Map object.
+
{{jsxref("Map.delete", "Map.prototype.delete(key)")}}
+
Returns true if an element in the Map object existed and has been removed, or false if the element does not exist. Map.prototype.has(key) will return false afterwards.
+
{{jsxref("Map.prototype.entries()")}}
+
Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.
+
{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}
+
Calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the this value for each callback.
+
{{jsxref("Map.get", "Map.prototype.get(key)")}}
+
Returns the value associated to the key, or undefined if there is none.
+
{{jsxref("Map.has", "Map.prototype.has(key)")}}
+
Returns a boolean asserting whether a value has been associated to the key in the Map object or not.
+
{{jsxref("Map.prototype.keys()")}}
+
Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
+
{{jsxref("Map.set", "Map.prototype.set(key, value)")}}
+
Sets the value for the key in the Map object. Returns the Map object.
+
{{jsxref("Map.prototype.values()")}}
+
Returns a new Iterator object that contains the values for each element in the Map object in insertion order.
+
{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}
+
Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.
+
+ +

Examples

+ +

Using the Map object

+ +
let myMap = new Map()
+
+let keyString = 'a string'
+let keyObj    = {}
+let keyFunc   = function() {}
+
+// setting the values
+myMap.set(keyString, "value associated with 'a string'")
+myMap.set(keyObj, 'value associated with keyObj')
+myMap.set(keyFunc, 'value associated with keyFunc')
+
+myMap.size              // 3
+
+// getting the values
+myMap.get(keyString)    // "value associated with 'a string'"
+myMap.get(keyObj)       // "value associated with keyObj"
+myMap.get(keyFunc)      // "value associated with keyFunc"
+
+myMap.get('a string')    // "value associated with 'a string'"
+                         // because keyString === 'a string'
+myMap.get({})            // undefined, because keyObj !== {}
+myMap.get(function() {}) // undefined, because keyFunc !== function () {}
+
+ +

Using NaN as Map keys

+ +

{{jsxref("NaN")}} can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other:

+ +
let myMap = new Map()
+myMap.set(NaN, 'not a number')
+
+myMap.get(NaN)
+// "not a number"
+
+let otherNaN = Number('foo')
+myMap.get(otherNaN)
+// "not a number"
+
+ +

Iterating Map with for..of

+ +

Maps can be iterated using a for..of loop:

+ +
let myMap = new Map()
+myMap.set(0, 'zero')
+myMap.set(1, 'one')
+
+for (let [key, value] of myMap) {
+  console.log(key + ' = ' + value)
+}
+// 0 = zero
+// 1 = one
+
+for (let key of myMap.keys()) {
+  console.log(key)
+}
+// 0
+// 1
+
+for (let value of myMap.values()) {
+  console.log(value)
+}
+// zero
+// one
+
+for (let [key, value] of myMap.entries()) {
+  console.log(key + ' = ' + value)
+}
+// 0 = zero
+// 1 = one
+
+ +

Iterating Map with forEach()

+ +

Maps can be iterated using the {{jsxref("Map.prototype.forEach", "forEach()")}} method:

+ +
myMap.forEach(function(value, key) {
+  console.log(key + ' = ' + value)
+})
+// 0 = zero
+// 1 = one
+
+ +

Relation with Array objects

+ +
let kvArray = [['key1', 'value1'], ['key2', 'value2']]
+
+// Use the regular Map constructor to transform a 2D key-value Array into a map
+let myMap = new Map(kvArray)
+
+myMap.get('key1') // returns "value1"
+
+// Use Array.from() to transform a map into a 2D key-value Array
+console.log(Array.from(myMap)) // Will show you exactly the same Array as kvArray
+
+// A succinct way to do the same, using the spread syntax
+console.log([...myMap])
+
+// Or use the keys() or values() iterators, and convert them to an array
+console.log(Array.from(myMap.keys())) // ["key1", "key2"]
+
+ +

Cloning and merging Maps

+ +

Just like Arrays, Maps can be cloned:

+ +
let original = new Map([
+  [1, 'one']
+])
+
+let clone = new Map(original)
+
+console.log(clone.get(1))       // one
+console.log(original === clone) // false (useful for shallow comparison)
+ +
+

Important: Keep in mind that the data itself is not cloned.

+
+ +

Maps can be merged, maintaining key uniqueness:

+ +
let first = new Map([
+  [1, 'one'],
+  [2, 'two'],
+  [3, 'three'],
+])
+
+let second = new Map([
+  [1, 'uno'],
+  [2, 'dos']
+])
+
+// Merge two maps. The last repeated key wins.
+// Spread operator essentially converts a Map to an Array
+let merged = new Map([...first, ...second])
+
+console.log(merged.get(1)) // uno
+console.log(merged.get(2)) // dos
+console.log(merged.get(3)) // three
+ +

Maps can be merged with Arrays, too:

+ +
let first = new Map([
+  [1, 'one'],
+  [2, 'two'],
+  [3, 'three'],
+])
+
+let second = new Map([
+  [1, 'uno'],
+  [2, 'dos']
+])
+
+// Merge maps with an array. The last repeated key wins.
+let merged = new Map([...first, ...second, [1, 'eins']])
+
+console.log(merged.get(1)) // eins
+console.log(merged.get(2)) // dos
+console.log(merged.get(3)) // three
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Map")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/math/index.html b/files/ar/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..dd3196e0ac --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,190 @@ +--- +title: رياضيات +slug: Web/JavaScript/Reference/Global_Objects/Math +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef}}
+ +

Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.

+ +

Description

+ +

Unlike the other global objects, Math is not a constructor. All properties and methods of Math are static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.

+ +

Properties

+ +
+
{{jsxref("Math.E")}}
+
Euler's constant and the base of natural logarithms, approximately 2.718.
+
{{jsxref("Math.LN2")}}
+
Natural logarithm of 2, approximately 0.693.
+
{{jsxref("Math.LN10")}}
+
Natural logarithm of 10, approximately 2.303.
+
{{jsxref("Math.LOG2E")}}
+
Base 2 logarithm of E, approximately 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Base 10 logarithm of E, approximately 0.434.
+
{{jsxref("Math.PI")}}
+
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
+
{{jsxref("Math.SQRT2")}}
+
Square root of 2, approximately 1.414.
+
+ +

Methods

+ +
+

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

+
+ +
+

Note that many math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

+
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
Returns the absolute value of a number.
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
Returns the arccosine of a number.
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
+
Returns the hyperbolic arccosine of a number.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
Returns the arcsine of a number.
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
+
Returns the hyperbolic arcsine of a number.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
Returns the arctangent of a number.
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
+
Returns the hyperbolic arctangent of a number.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
Returns the arctangent of the quotient of its arguments.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
+
Returns the cube root of a number.
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
Returns the smallest integer greater than or equal to a number.
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
+
Returns the number of leading zeroes of a 32-bit integer.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
Returns the cosine of a number.
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
+
Returns the hyperbolic cosine of a number.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
+
Returns subtracting 1 from exp(x).
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
Returns the largest integer less than or equal to a number.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
+
Returns the nearest single precision float representation of a number.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
+
Returns the square root of the sum of squares of its arguments.
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
+
Returns the result of a 32-bit integer multiplication.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
Returns the natural logarithm (loge, also ln) of a number.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
+
Returns the natural logarithm (loge, also ln) of 1 + x for a number x.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
+
Returns the base 10 logarithm of a number.
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
+
Returns the base 2 logarithm of a number.
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
Returns the largest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
Returns the smallest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
Returns base to the exponent power, that is, baseexponent.
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
Returns a pseudo-random number between 0 and 1.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
Returns the value of a number rounded to the nearest integer.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
+
Returns the sign of the x, indicating whether x is positive, negative or zero.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
Returns the sine of a number.
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
+
Returns the hyperbolic sine of a number.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
Returns the positive square root of a number.
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
Returns the tangent of a number.
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
+
Returns the hyperbolic tangent of a number.
+
Math.toSource() {{non-standard_inline}}
+
Returns the string "Math".
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
+
Returns the integer part of the number x, removing any fractional digits.
+
+ +

Extending the Math object

+ +

As with most of the built-in objects in JavaScript, the Math object can be extended with custom properties and methods. To extend the Math object, you do not use prototype. Instead, you directly extend Math:

+ +
Math.propName = propValue;
+Math.methodName = methodRef;
+ +

For instance, the following example adds a method to the Math object for calculating the greatest common divisor of a list of arguments.

+ +
/* Variadic function -- Returns the greatest common divisor of a list of arguments */
+Math.gcd = function() {
+    if (arguments.length == 2) {
+        if (arguments[1] == 0)
+            return arguments[0];
+        else
+            return Math.gcd(arguments[1], arguments[0] % arguments[1]);
+    } else if (arguments.length > 2) {
+        var result = Math.gcd(arguments[0], arguments[1]);
+        for (var i = 2; i < arguments.length; i++)
+            result = Math.gcd(result, arguments[i]);
+        return result;
+    }
+};
+ +

Try it:

+ +
console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/object/constructor/index.html b/files/ar/web/javascript/reference/global_objects/object/constructor/index.html new file mode 100644 index 0000000000..140d95a732 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/object/constructor/index.html @@ -0,0 +1,152 @@ +--- +title: Object.prototype.constructor +slug: Web/JavaScript/Reference/Global_Objects/Object/constructor +translation_of: Web/JavaScript/Reference/Global_Objects/Object/constructor +--- +
{{JSRef}}
+ +

بالرجوع إلى {{jsxref("Object")}}constructor ووظيفتها إنشاء حالات من الاوبجكت (الكائن) .نذكرك بأن قيمة الخصائص التي تشير إليها تلك الفانكشان تشير لنفسها ولا تشير إلى سلسة تحتوي على إسم الفانكشان القيمة تقرأ فقط قيم بدائية مثل 1true و "test".

+ +

الوصف

+ +

جميع الاوبجكت ( مع بعض الاستثائات نشأت مع Object.create(null)  ) وستملك وقتها جميعا خاصية الـ constructor . اما  الكائنات المنشأة بدون إستخدام الكونستراكتور بشكل صريح ( مثل  object & array literals )  ستملك أيضا خصائص الكونستركتور بشكل أساسي

+ +
var o = {};
+o.constructor === Object; // true
+
+var o = new Object;
+o.constructor === Object; // true
+
+var a = [];
+a.constructor === Array; // true
+
+var a = new Array;
+a.constructor === Array; // true
+
+var n = new Number(3);
+n.constructor === Number; // true
+
+ +

أمثلة

+ +

عرض الكونستركتور للأوبجكت

+ +

في المثال التالي قمنا بإنشاء بروتوتيب Tree و اوبجكت بإسم theTree  المثال هنا يعرض خصائص الـconstructor للكائن theTree

+ +
function Tree(name) {
+  this.name = name;
+}
+
+var theTree = new Tree('Redwood');
+console.log('theTree.constructor is ' + theTree.constructor);
+
+ +

عندما تقوم بكتابة الكود بعالية  ستحصل على النتيجة الاتية ليوضح لك أكثر  :-

+ +
theTree.constructor is function Tree(name) {
+  this.name = name;
+}
+
+ +

تغير الكونستركتور الخاص بالاوبجكت

+ +

The following example shows how to modify constructor value of generic objects. Only true, 1 and "test" will not be affected as they have read-only native constructors. This example shows that it is not always safe to rely on the constructor property of an object.

+ +
function Type () {}
+
+var types = [
+  new Array(),
+  [],
+  new Boolean(),
+  true,             // remains unchanged
+  new Date(),
+  new Error(),
+  new Function(),
+  function () {},
+  Math,
+  new Number(),
+  1,                // remains unchanged
+  new Object(),
+  {},
+  new RegExp(),
+  /(?:)/,
+  new String(),
+  'test'            // remains unchanged
+];
+
+for (var i = 0; i < types.length; i++) {
+  types[i].constructor = Type;
+  types[i] = [types[i].constructor, types[i] instanceof Type, types[i].toString()];
+}
+
+console.log(types.join('\n'));
+
+ +

This example displays the following output:

+ +
function Type() {},false,
+function Type() {},false,
+function Type() {},false,false
+function Boolean() {
+    [native code]
+},false,true
+function Type() {},false,Mon Sep 01 2014 16:03:49 GMT+0600
+function Type() {},false,Error
+function Type() {},false,function anonymous() {
+
+}
+function Type() {},false,function () {}
+function Type() {},false,[object Math]
+function Type() {},false,0
+function Number() {
+    [native code]
+},false,1
+function Type() {},false,[object Object]
+function Type() {},false,[object Object]
+function Type() {},false,/(?:)/
+function Type() {},false,/(?:)/
+function Type() {},false,
+function String() {
+    [native code]
+},false,test
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.2.4.1', 'Object.prototype.constructor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}{{Spec2('ESDraft')}} 
+ +

دعم  المتصفحات

+ +
+ + +

{{Compat("javascript.builtins.Object.constructor")}}

+
diff --git a/files/ar/web/javascript/reference/global_objects/object/index.html b/files/ar/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..2eb7c3bb18 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,182 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

The Object constructor creates an object wrapper.

+ +

Syntax

+ +
// Object initialiser or literal
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// Called as a constructor
+new Object([value])
+ +

Parameters

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
+
value
+
Any value.
+
+ +

Description

+ +

The Object constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

+ +

When called in a non-constructor context, Object behaves identically to new Object().

+ +

See also the object initializer / literal syntax.

+ +

Properties of the Object constructor

+ +
+
Object.length
+
Has a value of 1.
+
{{jsxref("Object.prototype")}}
+
Allows the addition of properties to all objects of type Object.
+
+ +

Methods of the Object constructor

+ +
+
{{jsxref("Object.assign()")}}
+
Copies the values of all enumerable own properties from one or more source objects to a target object.
+
{{jsxref("Object.create()")}}
+
Creates a new object with the specified prototype object and properties.
+
{{jsxref("Object.defineProperty()")}}
+
Adds the named property described by a given descriptor to an object.
+
{{jsxref("Object.defineProperties()")}}
+
Adds the named properties described by the given descriptors to an object.
+
{{jsxref("Object.entries()")}}
+
Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
+
{{jsxref("Object.freeze()")}}
+
Freezes an object: other code can't delete or change any properties.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Returns a property descriptor for a named property on an object.
+
{{jsxref("Object.getOwnPropertyDescriptors()")}}
+
Returns an object containing all own property descriptors for an object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
Returns an array of all symbol properties found directly upon a given object.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Returns the prototype of the specified object.
+
{{jsxref("Object.is()")}}
+
Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
+
{{jsxref("Object.isExtensible()")}}
+
Determines if extending of an object is allowed.
+
{{jsxref("Object.isFrozen()")}}
+
Determines if an object was frozen.
+
{{jsxref("Object.isSealed()")}}
+
Determines if an object is sealed.
+
{{jsxref("Object.keys()")}}
+
Returns an array containing the names of all of the given object's own enumerable string properties.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}}
+
Sets the prototype (i.e., the internal [[Prototype]] property).
+
{{jsxref("Object.values()")}}
+
Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
+
+ +

Object instances and Object prototype object

+ +

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
+ +

Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
+ +

Deleting a property from an object

+ +

There isn't any method in an Object itself to delete its own properties (e.g. like Map.prototype.delete()). To do so one has to use the delete operator.

+ +

Examples

+ +

Using Object given undefined and null types

+ +

The following examples store an empty Object object in o:

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Using Object to create Boolean objects

+ +

The following examples store {{jsxref("Boolean")}} objects in o:

+ +
// equivalent to o = new Boolean(true);
+var o = new Object(true);
+
+ +
// equivalent to o = new Boolean(false);
+var o = new Object(Boolean());
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object")}}

+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/string/index.html b/files/ar/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..4dd72a6601 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,314 @@ +--- +title: خيط +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - NeedsTranslation + - Reference + - String + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

The String global object is a constructor for strings, or a sequence of characters.

+ +

Syntax

+ +

String literals take the forms:

+ +
'string text'
+"string text"
+"中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
+ +

Strings can also be created using the String global object directly:

+ +
String(thing)
+ +

Parameters

+ +
+
thing
+
Anything to be converted to a string.
+
+ +

Template literals

+ +

Starting with ECMAScript 2015, string literals can also be so-called Template literals:

+ +
`hello world`
+`hello!
+ world!`
+`hello ${who}`
+escape `<a>${who}</a>`
+ +
+
+ +

Escape notation

+ +

Beside regular, printable characters, special characters can be encoded using escape notation:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnew line
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe Latin-1 character
+ +
+

Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.

+
+ +
+
+ +

Long literal strings

+ +

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

+ +

You can use the + operator to append multiple strings together, like this:

+ +
let longString = "This is a very long string which needs " +
+                 "to wrap across multiple lines because " +
+                 "otherwise my code is unreadable.";
+
+ +

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

+ +
let longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+
+ +

Both of these result in identical strings being created.

+ +

Description

+ +

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

+ +

Character access

+ +

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

+ +
return 'cat'.charAt(1); // returns "a"
+
+ +

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

+ +
return 'cat'[1]; // returns "a"
+
+ +

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

+ +

Comparing strings

+ +

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

+ +
var a = 'a';
+var b = 'b';
+if (a < b) { // true
+  console.log(a + ' is less than ' + b);
+} else if (a > b) {
+  console.log(a + ' is greater than ' + b);
+} else {
+  console.log(a + ' and ' + b + ' are equal.');
+}
+
+ +

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

+ +

Distinction between string primitives and String objects

+ +

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

+ +

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

+ +
var s_prim = 'foo';
+var s_obj = new String(s_prim);
+
+console.log(typeof s_prim); // Logs "string"
+console.log(typeof s_obj);  // Logs "object"
+
+ +

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

+ +
var s1 = '2 + 2';             // creates a string primitive
+var s2 = new String('2 + 2'); // creates a String object
+console.log(eval(s1));        // returns the number 4
+console.log(eval(s2));        // returns the string "2 + 2"
+
+ +

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

+ +

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

+ +
console.log(eval(s2.valueOf())); // returns the number 4
+
+ +
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
+ +

Properties

+ +
+
{{jsxref("String.prototype")}}
+
Allows the addition of properties to a String object.
+
+ +

Methods

+ +
+
{{jsxref("String.fromCharCode()")}}
+
Returns a string created by using the specified sequence of Unicode values.
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
Returns a string created by using the specified sequence of code points.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
Returns a string created from a raw template string.
+
+ +

String generic methods

+ +
+

String generics are non-standard, deprecated and will get removed near future.

+
+ +

The String instance methods are also available in Firefox as of JavaScript 1.6 (not part of the ECMAScript standard) on the String object for applying String methods to any object:

+ +
var num = 15;
+console.log(String.replace(num, /5/, '2'));
+
+ +

For migrating away from String generics, see also Warning: String.x is deprecated; use String.prototype.x instead.

+ +

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

+ +

String instances

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}
+ +

Methods

+ +

Methods unrelated to HTML

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}
+ +

HTML wrapper methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}
+ +

Examples

+ +

String conversion

+ +

It's possible to use String as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying toString(). It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:

+ +
var outputStrings = [];
+for (var i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.String")}}

+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/global_objects/string/startswith/index.html b/files/ar/web/javascript/reference/global_objects/string/startswith/index.html new file mode 100644 index 0000000000..94b059d593 --- /dev/null +++ b/files/ar/web/javascript/reference/global_objects/string/startswith/index.html @@ -0,0 +1,101 @@ +--- +title: String.prototype.startsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/startsWith +translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith +--- +
{{JSRef}}
+ +

startsWith()
+ .طريقة يمكنك تحقق بها إن كان نص يبدء بالعبارة ما و تعيد لك صحيح أو خطأ

+ +
{{EmbedInteractiveExample("pages/js/string-startswith.html")}}
+ + + +

تركيب الجملة | Syntax

+ +
str.startsWith(searchString[, position])
+ +

المعاملات | Parameters

+ +
+
searchString
+
العبارة المبحوث عنها فيالنص.
+
position {{optional_inline}}
+
مكان الذي يبدأ البحث منه فيالنص   الإفتراضي 0
+
+ +

القيمة العائدة | Return value

+ +

العائد يكون صحيح إذا وجد تطابق
+ و إن لم يجيد تطابق يعيد لك خطأ

+ +

الوصف | Description

+ +

هذه الطريقة حساسة إتجاه الحروف
+ case-sensitive

+ +

أمثلة | Examples

+ +

Using startsWith()

+ +
//startswith
+var str = 'To be, or not to be, that is the question.';
+
+console.log(str.startsWith('To be'));         // true
+console.log(str.startsWith('not to be'));     // false
+console.log(str.startsWith('not to be', 10)); // true
+
+ +

Polyfill

+ +

This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.startsWith() with the following snippet:

+ +
if (!String.prototype.startsWith) {
+    Object.defineProperty(String.prototype, 'startsWith', {
+        value: function(search, pos) {
+            pos = !pos || pos < 0 ? 0 : +pos;
+            return this.substring(pos, pos + search.length) === search;
+        }
+    });
+}
+
+ +

A more robust (fully ES2015 specification compliant), but less performant and compact, Polyfill is available on GitHub by Mathias Bynens.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ESDraft')}}
+ +

توافق مع متصفحات

+ + + +

{{Compat("javascript.builtins.String.startsWith")}}

+ +

ذات صلة

+ + diff --git "a/files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" "b/files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" new file mode 100644 index 0000000000..cb667fd3d8 --- /dev/null +++ "b/files/ar/web/javascript/reference/global_objects/\330\247\331\204\330\247\330\261\331\202\330\247\331\205/index.html" @@ -0,0 +1,12 @@ +--- +title: الارقام في الجافا سكربت +slug: Web/JavaScript/Reference/Global_Objects/الارقام +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +

 وهو كائن غلاف يستخدم لتمثيل ومعالجة الأرقام مثل  37  او 9.25 Numberمنشئ يحتوي على الثوابت وطرق للعمل مع الأرقام. يمكن تحويل قيم الأنواع الأخرى إلى أرقام باستخدام Number()الوظيفة.

+ +

جافا سكريبت رقم نوع عبارة عن قيمة مزدوجة الدقة بتنسيق IEEE 754 تنسيق ثنائي 64 بت ذات ، كما هو الحال doubleفي Java أو C #. هذا يعني أنه يمكن أن يمثل قيمًا كسرية ، ولكن هناك بعض الحدود لما يمكن تخزينه. يحتفظ فقط بحوالي   17 رقم  منزلاً عشريًا من الدقة ؛ الحساب يخضع للتقريب . أكبر قيمة يمكن أن يحملها رقم هي حوالي 1.8 × 10 308 . يتم استبدال الأعداد التي تتجاوز ذلك بثابت الرقم الخاص Infinity.

+ +

الرقم الحرفي مثل 37كود JavaScript هو قيمة فاصلة عائمة ، وليس عددًا صحيحًا. لا يوجد نوع عدد صحيح منفصل في الاستخدام اليومي الشائع. (يحتوي JavaScript الآن على BigIntنوع ، لكنه لم يتم تصميمه ليحل محل Number للاستخدامات اليومية. 37لا يزال رقمًا ، وليس BigInt.)

+ +

يمكن أيضًا التعبير عن الرقم بأشكال حرفية مثل 0b101، 0o13، 0x0A. تعرف على المزيد حول العددي قواعد المعجم هنا .

diff --git a/files/ar/web/javascript/reference/index.html b/files/ar/web/javascript/reference/index.html new file mode 100644 index 0000000000..db41d77223 --- /dev/null +++ b/files/ar/web/javascript/reference/index.html @@ -0,0 +1,50 @@ +--- +title: مرجع جافا سكريبت +slug: Web/JavaScript/Reference +tags: + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference +--- +
{{JsSidebar}}
+ +

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

+ +

Global Objects

+ +

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}
+ +

Statements

+ +

This chapter documents all the JavaScript statements and declarations.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
+ +

Expressions and operators

+ +

This chapter documents all the JavaScript expressions and operators.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
+ +

Functions

+ +

This chapter documents how to work with JavaScript functions to develop your applications.

+ + + +

Additional reference pages

+ + diff --git a/files/ar/web/javascript/reference/operators/destructuring_assignment/index.html b/files/ar/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..d926351173 --- /dev/null +++ b/files/ar/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,428 @@ +--- +title: Destructuring assignment +slug: Web/JavaScript/Reference/Operators/Destructuring_assignment +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +
{{jsSidebar("Operators")}}
+ +
الإسناد بالتفكيك هو تعبير جافاسكربت يجعل من الممكن فك القيم من المصفوفات ( Arrays ) أو الخصائص من الكائنات ( Objects ) إلى متغيرات مميزة.
+ +
+ +
{{EmbedInteractiveExample("pages/js/expressions-destructuringassignment.html", "taller")}}
+ + + +

Syntax

+ +
let a, b, rest;
+[a, b] = [10, 20];
+console.log(a); // 10
+console.log(b); // 20
+
+[a, b, ...rest] = [10, 20, 30, 40, 50];
+console.log(a); // 10
+console.log(b); // 20
+console.log(rest); // [30, 40, 50]
+
+({ a, b } = { a: 10, b: 20 });
+console.log(a); // 10
+console.log(b); // 20
+
+
+// Stage 4(finished) proposal
+({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
+console.log(a); // 10
+console.log(b); // 20
+console.log(rest); // {c: 30, d: 40}
+
+ +

التفاصيل

+ +

توفر تعبيرات الكائن (Object) والمصفوفة (Array) طريقة سهلة لإنشاء حزم بيانات مخصصة.

+ +
const x = [1, 2, 3, 4, 5];
+
+ +

يَستخدِم الإسناد بالتفكيك (destructuring assignment) بنية مماثلة، ولكن على الجانب الأيسر من المهمة لتحديد القيم التي يجب فكها من مصدر المتغير الأساسي.

+ +
const x = [1, 2, 3, 4, 5];
+const [y, z] = x;
+console.log(y); // 1
+console.log(z); // 2
+
+ +

تشبه هذه الإمكانية الميزات الموجودة بلغات مثل Perl و Python.

+ +

+ +

تفكيك المصفوفات

+ +

تعيين المتغير الأساسي

+ +
const foo = ['one', 'two', 'three'];
+
+const [red, yellow, green] = foo;
+console.log(red); // "one"
+console.log(yellow); // "two"
+console.log(green); // "three"
+
+ +

Assignment separate from declaration

+ +

A variable can be assigned its value via destructuring separate from the variable's declaration.

+ +
let a, b;
+
+[a, b] = [1, 2];
+console.log(a); // 1
+console.log(b); // 2
+
+ +

Default values

+ +

A variable can be assigned a default, in the case that the value unpacked from the array is undefined.

+ +
let a, b;
+
+[a=5, b=7] = [1];
+console.log(a); // 1
+console.log(b); // 7
+
+ +

Swapping variables

+ +

Two variables values can be swapped in one destructuring expression.

+ +

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick).

+ +
let a = 1;
+let b = 3;
+
+[a, b] = [b, a];
+console.log(a); // 3
+console.log(b); // 1
+
+const arr = [1,2,3];
+[arr[2], arr[1]] = [arr[1], arr[2]];
+console.log(arr); // [1,3,2]
+
+
+ +

Parsing an array returned from a function

+ +

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

+ +

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

+ +
function f() {
+  return [1, 2];
+}
+
+let a, b;
+[a, b] = f();
+console.log(a); // 1
+console.log(b); // 2
+
+ +

Ignoring some returned values

+ +

You can ignore return values that you're not interested in:

+ +
function f() {
+  return [1, 2, 3];
+}
+
+const [a, , b] = f();
+console.log(a); // 1
+console.log(b); // 3
+
+const [c] = f();
+console.log(c); // 1
+
+ +

You can also ignore all returned values:

+ +
[,,] = f();
+
+ +

Assigning the rest of an array to a variable

+ +

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

+ +
const [a, ...b] = [1, 2, 3];
+console.log(a); // 1
+console.log(b); // [2, 3]
+ +

Be aware that a {{jsxref("SyntaxError")}} will be thrown if a trailing comma is used on the left-hand side with a rest element:

+ +
const [a, ...b,] = [1, 2, 3];
+
+// SyntaxError: rest element may not have a trailing comma
+// Always consider using rest operator as the last element
+
+ +

Unpacking values from a regular expression match

+ +

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

+ +
function parseProtocol(url) {
+  const parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
+  if (!parsedURL) {
+    return false;
+  }
+  console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
+
+  const [, protocol, fullhost, fullpath] = parsedURL;
+  return protocol;
+}
+
+console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"
+
+ +

Object destructuring

+ +

Basic assignment

+ +
const user = {
+    id: 42,
+    is_verified: true
+};
+
+const {id, is_verified} = user;
+
+console.log(id); // 42
+console.log(is_verified); // true
+
+ +

Assignment without declaration

+ +

A variable can be assigned its value with destructuring separate from its declaration.

+ +
let a, b;
+
+({a, b} = {a: 1, b: 2});
+ +
+

Notes: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

+ +

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

+ +

However, ({a, b} = {a: 1, b: 2}) is valid, as is const {a, b} = {a: 1, b: 2}

+ +

Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

+
+ +

Assigning to new variable names

+ +

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

+ +
const o = {p: 42, q: true};
+const {p: foo, q: bar} = o;
+
+console.log(foo); // 42
+console.log(bar); // true
+ +

Here, for example, const {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo.

+ +

Default values

+ +

A variable can be assigned a default, in the case that the value unpacked from the object is undefined.

+ +
const {a = 10, b = 5} = {a: 3};
+
+console.log(a); // 3
+console.log(b); // 5
+ +

Assigning to new variables names and providing default values

+ +

A property can be both 1) unpacked from an object and assigned to a variable with a different name and 2) assigned a default value in case the unpacked value is undefined.

+ +
const {a: aa = 10, b: bb = 5} = {a: 3};
+
+console.log(aa); // 3
+console.log(bb); // 5
+
+ +

Unpacking fields from objects passed as function parameter

+ +
const user = {
+  id: 42,
+  displayName: 'jdoe',
+  fullName: {
+    firstName: 'John',
+    lastName: 'Doe'
+  }
+};
+
+function userId({id}) {
+  return id;
+}
+
+function whois({displayName, fullName: {firstName: name}}) {
+  return `${displayName} is ${name}`;
+}
+
+console.log(userId(user)); // 42
+console.log(whois(user));  // "jdoe is John"
+ +

This unpacks the id, displayName and firstName from the user object and prints them.

+ +

Setting a function parameter's default value

+ +
function drawChart({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) {
+  console.log(size, coords, radius);
+  // do some chart drawing
+}
+
+drawChart({
+  coords: {x: 18, y: 30},
+  radius: 30
+});
+ +
+

In the function signature for drawChart above, the destructured left-hand side is assigned to an empty object literal on the right-hand side: {size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}. You could have also written the function without the right-hand side assignment. However, if you leave out the right-hand side assignment, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can simply call drawChart() without supplying any parameters. The current design is useful if you want to be able to call the function without supplying any parameters, the other can be useful when you want to ensure an object is passed to the function.

+
+ +

Nested object and array destructuring

+ +
const metadata = {
+  title: 'Scratchpad',
+  translations: [
+    {
+      locale: 'de',
+      localization_tags: [],
+      last_edit: '2014-04-14T08:43:37',
+      url: '/de/docs/Tools/Scratchpad',
+      title: 'JavaScript-Umgebung'
+    }
+  ],
+  url: '/en-US/docs/Tools/Scratchpad'
+};
+
+let {
+  title: englishTitle, // rename
+  translations: [
+    {
+       title: localeTitle, // rename
+    },
+  ],
+} = metadata;
+
+console.log(englishTitle); // "Scratchpad"
+console.log(localeTitle);  // "JavaScript-Umgebung"
+ +

For of iteration and destructuring

+ +
const people = [
+  {
+    name: 'Mike Smith',
+    family: {
+      mother: 'Jane Smith',
+      father: 'Harry Smith',
+      sister: 'Samantha Smith'
+    },
+    age: 35
+  },
+  {
+    name: 'Tom Jones',
+    family: {
+      mother: 'Norah Jones',
+      father: 'Richard Jones',
+      brother: 'Howard Jones'
+    },
+    age: 25
+  }
+];
+
+for (const {name: n, family: {father: f}} of people) {
+  console.log('Name: ' + n + ', Father: ' + f);
+}
+
+// "Name: Mike Smith, Father: Harry Smith"
+// "Name: Tom Jones, Father: Richard Jones"
+
+ +

Computed object property names and destructuring

+ +

Computed property names, like on object literals, can be used with destructuring.

+ +
let key = 'z';
+let {[key]: foo} = {z: 'bar'};
+
+console.log(foo); // "bar"
+
+ +

Rest in Object Destructuring

+ +

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

+ +
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
+a; // 10
+b; // 20
+rest; // { c: 30, d: 40 }
+ +

Invalid JavaScript identifier as a property name

+ +

Destructuring can be used with property names that are not valid JavaScript {{glossary("Identifier", "identifiers")}} by providing an alternative identifier that is valid.

+ +
const foo = { 'fizz-buzz': true };
+const { 'fizz-buzz': fizzBuzz } = foo;
+
+console.log(fizzBuzz); // "true"
+
+ +

Combined Array and Object Destructuring

+ +

Array and Object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

+ +
const props = [
+  { id: 1, name: 'Fizz'},
+  { id: 2, name: 'Buzz'},
+  { id: 3, name: 'FizzBuzz'}
+];
+
+const [,, { name }] = props;
+
+console.log(name); // "FizzBuzz"
+
+ +

The prototype chain is looked up when the object is deconstructed 

+ +

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

+ +
let obj = {self: '123'};
+obj.__proto__.prot = '456';
+const {self, prot} = obj;
+// self "123"
+// prot "456"(Access to the prototype chain)
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.operators.destructuring")}}

+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/operators/index.html b/files/ar/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..a5dc098a4f --- /dev/null +++ b/files/ar/web/javascript/reference/operators/index.html @@ -0,0 +1,302 @@ +--- +title: Expressions and operators +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - NeedsTranslation + - Operators + - TopicStub +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

This chapter documents all the JavaScript language operators, expressions and keywords.

+ +

Expressions and operators by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Primary expressions

+ +

Basic keywords and general expressions in JavaScript.

+ +
+
{{jsxref("Operators/this", "this")}}
+
The this keyword refers to the function's execution context.
+
{{jsxref("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{jsxref("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{jsxref("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{jsxref("Operators/yield", "yield")}}
+
Pause and resume a generator function.
+
{{jsxref("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{experimental_inline}} {{jsxref("Operators/async_function", "async function*")}}
+
The async function defines an async function expression.
+
{{experimental_inline}} {{jsxref("Operators/await", "await")}}
+
Pause and resume an async function and wait for the promise's resolution/rejection.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
new.target
+
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
+
{{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{jsxref("Operators/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Unary operators

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Arithmetic operators

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +
+
{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
+
Exponentiation operator.
+
+ +

Relational operators

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +
+

Note: => is not an operator, but the notation for Arrow functions.

+
+ +

Equality operators

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Equality operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Inequality operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identity operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidentity operator.
+
+ +

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Binary bitwise operators

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwise AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwise OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwise XOR.
+
+ +

Binary logical operators

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logical AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logical OR.
+
+ +

Conditional (ternary) operator

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Assignment operators

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

+
+
+ +

Comma operator

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
+
+ +

Non-standard features

+ +
+
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
+
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/operators/new/index.html b/files/ar/web/javascript/reference/operators/new/index.html new file mode 100644 index 0000000000..3b39e0cf4e --- /dev/null +++ b/files/ar/web/javascript/reference/operators/new/index.html @@ -0,0 +1,178 @@ +--- +title: new operator +slug: Web/JavaScript/Reference/Operators/new +tags: + - HTTP + - OpenPractices + - البروتوكولات + - بحث + - لغة البرمجة +translation_of: Web/JavaScript/Reference/Operators/new +--- +
9 9090 jsSidebar ("عوامل التشغيل")}}
+ +

في newالمشغل يتيح للمطورين إنشاء مثيل من نوع الكائن المعرفة من قبل المستخدم أو واحد من أنواع الكائنات المضمنة التي لديه وظيفة المنشئ.

+ +
{{EmbedInteractiveExample ("pages / js / expressions-newoperator.html")}}
+ +

بناء الجملة

+ +
new constructor[([arguments])]
+ +

المعلمات

+ +
+
constructor
+
فئة أو وظيفة تحدد نوع مثيل الكائن.
+
+ +
+
arguments
+
قائمة القيم التي constructorسيتم الاتصال بها.
+
+ +

وصف

+ +

تقوم newالكلمة الرئيسية بالأشياء التالية:

+ +
    +
  1. ينشئ كائن JavaScript عاديًا فارغًا ؛
  2. +
  3. روابط (تحدد منشئ) هذا الكائن إلى كائن آخر ؛
  4. +
  5. يمر كائن تم إنشاؤه حديثا من الخطوة 1 كما في thisالسياق؛
  6. +
  7. يعود thisإذا لم الدالة بإرجاع كائن.
  8. +
+ +

يتطلب إنشاء كائن معرف من قبل المستخدم خطوتين:

+ +
    +
  1. حدد نوع الكائن عن طريق كتابة دالة.
  2. +
  3. إنشاء مثيل للكائن باستخدام new.
  4. +
+ +

لتحديد نوع كائن ، قم بإنشاء وظيفة لنوع الكائن تحدد اسمه وخصائصه. يمكن أن يكون للكائن خاصية تكون في حد ذاتها كائنًا آخر. انظر الأمثلة أدناه.

+ +

عند تنفيذ الكود ، تحدث الأشياء التالية:new Foo(...)

+ +
    +
  1. يتم إنشاء كائن جديد ، وراثة من Foo.prototype.
  2. +
  3. Fooيتم استدعاء دالة المُنشئ بالوسيطات المحددة ، وتكون thisمرتبطة بالكائن الذي تم إنشاؤه حديثًا. يكافئ ، على سبيل المثال ، إذا لم يتم تحديد قائمة وسيطة ، يتم استدعاؤه بدون وسيطات.new Foonew Foo()Foo
  4. +
  5. يصبح الكائن (ليس فارغًا ، أو خطأ ، أو 3.1415 أو أنواعًا أولية أخرى) التي تُرجعها دالة المُنشئ نتيجة newالتعبير بالكامل . إذا لم تُرجع دالة المُنشئ كائنًا بشكل صريح ، فسيتم استخدام الكائن الذي تم إنشاؤه في الخطوة 1 بدلاً من ذلك. (عادةً لا تُرجع المنشئات قيمة ، لكن يمكنهم اختيار القيام بذلك إذا كانوا يريدون تجاوز عملية إنشاء الكائن العادية.)
  6. +
+ +

يمكنك دائمًا إضافة خاصية إلى كائن محدد مسبقًا. على سبيل المثال ، car1.color = "black"تضيف العبارة خاصية colorإلى car1، وتخصص لها قيمة " black". ومع ذلك ، هذا لا يؤثر على أي كائنات أخرى. لإضافة الخاصية الجديدة إلى جميع الكائنات من نفس النوع ، يجب إضافة الخاصية إلى تعريف Carنوع الكائن.

+ +

يمكنك إضافة خاصية مشتركة إلى نوع كائن محدد مسبقًا باستخدام Function.prototypeالخاصية. يحدد هذا الخاصية التي يتم مشاركتها بواسطة جميع الكائنات التي تم إنشاؤها باستخدام هذه الوظيفة ، بدلاً من مثيل واحد فقط من نوع الكائن. تضيف التعليمة البرمجية التالية خاصية لون مع قيمة "original color"لكل كائنات النوع Car، ثم تكتب فوق تلك القيمة بالسلسلة " black" فقط في كائن المثيل car1. لمزيد من المعلومات ، انظر النموذج الأولي .

+ +
function Car() {}
+car1 = new Car();
+car2 = new Car();
+
+console.log(car1.color);    // undefined
+
+Car.prototype.color = 'original color';
+console.log(car1.color);    // 'original color'
+
+car1.color = 'black';
+console.log(car1.color);    // 'black'
+
+console.log(Object.getPrototypeOf(car1).color); // 'original color'
+console.log(Object.getPrototypeOf(car2).color); // 'original color'
+console.log(car1.color);   // 'black'
+console.log(car2.color);   // 'original color'
+
+ +
+

إذا لم تكتب newعامل التشغيل ، فسيتم استدعاء دالة الباني مثل أي دالة عادية ، دون إنشاء كائن. في هذه الحالة ، قيمة thisمختلفة أيضًا.

+
+ +

أمثلة

+ +

نوع الكائن ومثيل الكائن

+ +

لنفترض أنك تريد إنشاء نوع كائن للسيارات. تريد أن يتم استدعاء هذا النوع من الكائنات Car، وتريد أن يكون لها خصائص لـ make و model و year. للقيام بذلك ، يمكنك كتابة الوظيفة التالية:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

الآن يمكنك إنشاء كائن يسمى على myCarالنحو التالي:

+ +
var myCar = new Car('Eagle', 'Talon TSi', 1993);
+
+ +

تقوم هذه العبارة بإنشاء myCarوتعيين القيم المحددة لخصائصها. ثم قيمة myCar.makeالسلسلة "النسر" ، myCar.yearهو العدد الصحيح 1993 ، وهلم جرا.

+ +

يمكنك إنشاء أي عدد من carالكائنات عن طريق المكالمات إلى new. فمثلا:

+ +
var kensCar = new Car('Nissan', '300ZX', 1992);
+
+ +

خاصية الكائن التي هي نفسها كائن آخر

+ +

لنفترض أنك قمت بتعريف كائن يسمى على PersSexonالنحو التالي:

+ +
function Person(name, age, sex) {XxxXxx
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

ثم قم بإنشاء كائنين جديدين على Personالنحو التالي:

+ +
var rand = new Person('Rand McNally', 33, 'M');
+var ken = new Person('Ken Jones', 39, 'M');
+
+ +

ثم يمكنك إعادة كتابة تعريف Carلتضمين ownerخاصية تأخذ Personكائنًا ، على النحو التالي:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+
+ +

لإنشاء كائنات جديدة ، يمكنك بعد ذلك استخدام ما يلي:

+ +
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
+var car2 = new Car('Nissan', '300ZX', 1992, ken);
+
+ +

بدلا من تمرير سلسلة حرفية أو عدد صحيح القيمة عند إنشاء كائنات جديدة، والبيانات المذكورة أعلاه تمر الكائنات randو kenكمعلمات للمالكي. لمعرفة اسم مالك الموقع car2، يمكنك الوصول إلى الخاصية التالية:

+ +
car2.owner.name
+
+ +

مواصفات

+ + + + + + + + + + + + +
تخصيص
{{SpecName ('ESDraft'، '# sec-new-worker'، 'The new Operator')}}
+ +

التوافق المتصفح

+ + + +

{{Compat ("javascript.operators.new")}}

+ +

أنظر أيضا

+ + diff --git a/files/ar/web/javascript/reference/operators/object_initializer/index.html b/files/ar/web/javascript/reference/operators/object_initializer/index.html new file mode 100644 index 0000000000..b6df949722 --- /dev/null +++ b/files/ar/web/javascript/reference/operators/object_initializer/index.html @@ -0,0 +1,403 @@ +--- +title: Object initializer تهيئة الكائن +slug: Web/JavaScript/Reference/Operators/Object_initializer +translation_of: Web/JavaScript/Reference/Operators/Object_initializer +--- +
{{JsSidebar("Operators")}}
+ +

 

+ +
+

يمكن تهيئة الكائنات باستخدام ()new Object او ()Object.create او باستخدام مهيئ الكائن (Object initializer). مهيئ الكائن هو عبارة عن قائمة من الخصائص، وكل خاصية من هذه الخصائص عبارة عن زوجين وهما، اسم الخاصية وقيمة الخاصية، يفصل بين كل زوجين بفاصلة، يمكن لهذه القائمة ان تحتوي على صفر او اكثر من هذه الازواج، محاطة بأقواس متعرجة ({}).

+ +

Syntax

+ +
var o = {};
+var o = {a: 'foo', b: 42, c: {}};
+
+var a = 'foo', b = 42, c = {};
+var o = {a: a, b: b, c: c};
+
+var o = {
+  property: function ([parameters]) {},
+  get property() {},
+  set property(value) {}
+};
+
+ +

New notations in ECMAScript 2015

+ +

يرجى الاطلاع على جدول التوافق اسفل الصفحة. هذه التعليمات البرمجية ستؤدي إلى أخطاء syntax errors، في البيئات الغير الداعمة.

+ +
// Shorthand property names (ES2015)
+var a = 'foo', b = 42, c = {};
+var o = {a, b, c};
+
+// Shorthand method names (ES2015)
+var o = {
+  property([parameters]) {},
+  get property() {},
+  set property(value) {}
+};
+
+// Computed property names (ES2015)
+var prop = 'foo';
+var o = {
+  [prop]: 'hey',
+  ['b' + 'ar']: 'there'
+};
+ +

الوصف

+ +

مهيئ الكائن هو تعبير عن كيفية وصف وتهيئة الكائن {{jsxref("Object")}}. تتكون الكائنات من الخصائص، والتي يتم استخدامها لوصف الكائن. قيمة خاصية الكائن يمكن أن تحتوي على أنواع البيانات الأولية {{Glossary("primitive")}} كما يمكنها ايضا ان تحتوي على كائنات اخرى.

+ +

إنشاء الكائنات

+ +

يمكن إنشاء كائن فارغ بدون خصائص هكذا:

+ +
var object = {};
+ +

ميزة هذا literal او المهئ هي انه يمكنك سريعا من انشاء الكائنات وخصائصها داخل الأقواس المتعرجة. يمكنك ببساطة انشاء قائمة مكونة من زوجين key: value مفصولة بفاصلة. تقوم التعليمة البرمجية التالية بانشاء كائن مع ثلاثة خصائص والمفاتيح هي "foo", "age" و "baz". وقيم هذه المفاتيح هي string "bar", a number 42، فيما قيمة المفتاح "baz" عبارة عن كائن هو ايضا له مفتاح وقيمة.

+ +
var object = {
+  foo: 'bar',
+  age: 42,
+  baz: {myProp: 12}
+}
+ +

الوصول إلى الخصائص

+ +

حالما تقوم بإنشاء كائن، سترغب في قراءة الخصائص أو تغييرها. يمكن الوصول إلى خصائص الكائن باستخدام نقطة التدوين او عن طريق الاقواس المربعة. راجع property accessors لمزيد من المعلومات.

+ +
object.foo; // "bar"
+object['age']; // 42
+
+object.foo = 'baz';
+
+ +

تعريف الخصائص

+ +

تعلمنا للتو كيفية التعبير عن الخصائص باستخدام المهيئ. تجدر الإشارة الى انه في كثير من الأحيان، سترغب في تمرير متغيرات الى الكائن. يمكنك تمريها على هذا النحو:

+ +
var a = 'foo',
+    b = 42,
+    c = {};
+
+var o = {
+  a: a,
+  b: b,
+  c: c
+};
+ +

ECMAScript 2015، جاءت بطريقة مختصرة لتحقيق نفس الغرض:

+ +
var a = 'foo',
+    b = 42,
+    c = {};
+
+// Shorthand property names (ES2015)
+var o = {a, b, c};
+
+// In other words,
+console.log((o.a === {a}.a)); // true
+
+ +

أسماء الخصائص المكررة

+ +

عند استخدام الخصائص باسماء مكررة، سوف تقوم الخاصية الثانية بالكتابة فوق  الأولى.

+ +
var a = {x: 1, x: 2};
+console.log(a); // {x: 2}
+
+ +

في ECMAScript 5 strict mode تكرار اسماء الخصائص سينتج عنها اخطاء {{jsxref("SyntaxError")}}.

+ +
function haveES2015DuplicatePropertySemantics() {
+  'use strict';
+  try {
+    ({prop: 1, prop: 2});
+
+    // No error thrown, duplicate property names allowed in strict mode
+    return true;
+  } catch(e) {
+    // Error thrown, duplicates prohibited in strict mode
+    return false;
+  }
+}
+ +

تعريف الوظائف

+ +

خاصية الكائن يمكن أن تشير أيضا إلى الوظائف function او getter او setter.

+ +
var o = {
+  property: function ([parameters]) {},
+  get property() {},
+  set property(value) {}
+};
+ +

في ECMAScript 2015، اصبح الاختصار متاحا، حيث أن الكلمة المحجوزة function لم تعد ضرورية.

+ +
// Shorthand method names (ES2015)
+var o = {
+  property([parameters]) {},
+  get property() {},
+  set property(value) {},
+  * generator() {}
+};
+
+ +

في ECMAScript 2015، هناك طريقة لاختصار تعريف الخصائص التي قيمها generator functions :

+ +
var o = {
+  * generator() {
+    ...........
+  }
+};
+ +

في ECMAScript 5، سوف تكتب هكذا (لكن لاحظ أن ES5 قد لا توجد مولدات):

+ +
var o = {
+  generator: function *() {
+    ...........
+  }
+};
+ +

لمزيد من المعلومات والأمثلة حول الوظائف، راجع method definitions.

+ +

أسماء الخصائص المحوسبة

+ +

ابتداءا من ECMAScript 2015، مهئ الكائن اصبح يدعم اسماء الخصائص المحوسبة. والتي تسمح لك بوضع التعبير بين أقواس مربعة []، والتي ستعتمد كاسم للخاصية. وهي متسقة مع الاقواس المربعة التي تستخدم للوصول الى الخصائص، property accessor والتي قد تستخدم بالفعل لقراءة وتعيين الخصائص. الآن يمكنك استخدام نفس التعبير المستخدم في object literals، هكذا:

+ +
// Computed property names (ES2015)
+var i = 0;
+var a = {
+  ['foo' + ++i]: i,
+  ['foo' + ++i]: i,
+  ['foo' + ++i]: i
+};
+
+console.log(a.foo1); // 1
+console.log(a.foo2); // 2
+console.log(a.foo3); // 3
+
+var param = 'size';
+var config = {
+  [param]: 12,
+  ['mobile' + param.charAt(0).toUpperCase() + param.slice(1)]: 4
+};
+
+console.log(config); // {size: 12, mobileSize: 4}
+ +

Prototype mutation

+ +

الخاصية المعرفة على هذا الشكل  proto__: value__ او proto__": value__" لا تقوم بإنشاء خاصية جديدة باسم  __proto__. بل تقوم  بتغيير [[Prototype]] الكائن نفسه، وذالك من خلال اسناد قيمة له تكون عبارة عن كائن اخر او null. (إذا كانت القيمة المسندة ليست كائن أو null، فلا يتم تغيير شئ في الكائن) على سبيل المثال:

+ +
var obj1 = {x: 10};
+
+var obj2 = {
+	y: 20,
+    __proto__: obj1
+};
+console.log( obj2.x ); // log: 10 
+ +

تبين التعليمة البرمجية التالية، بعض التحققات من بعض انواع التغييرات:

+ +
var obj1 = {};
+assert(Object.getPrototypeOf(obj1) === Object.prototype);  // true
+
+var obj2 = {__proto__: null};
+assert(Object.getPrototypeOf(obj2) === null);              // true
+
+var protoObj = {};
+var obj3 = {'__proto__': protoObj};
+assert(Object.getPrototypeOf(obj3) === protoObj);          // true
+
+var obj4 = {__proto__: 'not an object or null'};
+assert(Object.getPrototypeOf(obj4) === Object.prototype);  // true
+assert(!obj4.hasOwnProperty('__proto__'));                 // true
+
+ +

لا يسمح بتغيير ال prototype الا مرة واحدة في object literal، واكثر من تغيير في ال prototype سيؤدي الى syntax error.

+ +

الخواص التي لا تستخدم النقطتين (:) تصبح خواص عادية وتتصرف كاي اسم اخر، وليس لها علاقة بتغيير ال prototype:

+ +
var __proto__ = 'variable';
+
+var obj1 = {__proto__};
+assert(Object.getPrototypeOf(obj1) === Object.prototype);
+assert(obj1.hasOwnProperty('__proto__'));
+assert(obj1.__proto__ === 'variable');
+
+var obj2 = {__proto__() { return 'hello'; }};
+assert(obj2.__proto__() === 'hello');
+
+var obj3 = {['__prot' + 'o__']: 17};
+assert(obj3.__proto__ === 17);
+
+ +

Object literal notation vs JSON

+ +

ال object literal notation ليس هو نفسه JavaScript Object Notation (JSON). على الرغم من أنها تبدو مشابهة، الا ان هنالك اختلافات كبيرة بينهما:

+ + +
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}initial definition.
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}getter and setter added.
{{SpecName('ES2015', '#sec-object-initializer', 'Object Initializer')}}{{Spec2('ES2015')}}Shorthand method/property names and computed property names added.
{{SpecName('ESDraft', '#sec-object-initializer', 'Object Initializer')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}111
Computed property names{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}347.1
Shorthand property names{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("33")}}{{CompatNo}}349
Shorthand method names{{CompatChrome(42.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}349
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}111{{CompatChrome(1.0)}}
Computed property names{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("34")}}{{CompatNo}}347.1{{CompatNo}}
Shorthand property names{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("33")}}{{CompatNo}}349{{CompatNo}}
Shorthand method names{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile("34")}}{{CompatNo}}349{{CompatChrome(42.0)}}
+
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/operators/operator_precedence/index.html b/files/ar/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..8b71a69143 --- /dev/null +++ b/files/ar/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,420 @@ +--- +title: أسبقية العوامل +slug: Web/JavaScript/Reference/Operators/Operator_Precedence +tags: + - أسبقية العوامل + - جافا سكربت + - عوامل رياضية +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +

أسبقية العوامل تحدد الطريقة التي يتم بها تعامل كل من العوامل مع بعضها. العوامل ذات الأسبقية العليا تسبق العوامل ذات الأسبقية المنخفضة.

+ +
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
+ + + +

الترابطات 

+ +

تحدد الترابطات الطريقة التي يتم بها تحليل العوامل التي لها نفس الأسبقية. على سبيل المثال، لنقل أن:

+ +
a OP b OP c
+
+ +

تعني كلمة رابط - يسار (من اليسار إلى اليمين) أنها تتم معالجتها كـ a OP b) OP c) ، بينما تعني رابط - يمين (من اليمين إلى اليسار) أنها تُفسَّر على أنها (a OP (b OP c. عوامل التعيين هي رابط-يمين، حيث يمكنك كتابة:

+ +
a = b = 5;
+
+ +

مع النتيجة المتوقعة أن تحصل a و b على القيمة 5. وذلك لأن عامل التعيين يُرجع القيمة التي تم تعيينها. أولاً، يتم تعيين b على 5. ثم يتم تعيين a أيضًا على 5 ، قيمة الإرجاع b = 5 ، ويعرف أيضًا باسم المعامل الأيمن للتعيين.

+ +

أمثلة:

+ +
3 > 2 && 2 > 1
+// returns true تعيد لنا صح
+
+3 > 2 > 1
+// returns false because 3 > 2 is true, and true > 1 is false تعيد خطأ لأن 3>2 هي صحيحة، وصح > 1 هو خطأ
+// Adding parentheses makes things clear: (3 > 2) > 1 إضافة الأقواس تجعل كل شيء واضح: (3>2) 1
+ +

الجدول

+ +

الجدول التالي مرتب من (20) الأعلى أسبقية إلى الأقل وهو (1).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PrecedenceOperator typeAssociativityIndividual operators
21{{jsxref("Operators/Grouping", "Grouping", "", 1)}} تجميعn/a( … )
20{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation", 1)}} الوصول الى عنصر +

left-to-right

+ +

من اليسار الى اليمين

+
… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation", 1)}} الوصول لعنصر محسوب +

left-to-right

+ +

من اليسار الى اليمين

+
… [ … ]
{{jsxref("Operators/new","new")}} (with argument list) جديد مع (قائمة معاملات)n/anew … ( … )
Function Call استدعاء دالة +

left-to-right

+ +

من اليسار الى اليمين

+
… ( )
Optional chaining تسلسل اختياري +

left-to-right

+ +

من اليسار الى اليمين

+
?.
19{{jsxref("Operators/new","new")}} (without argument list) جديد .. بدون قائمة معاملات +

right-to-left

+ +

من اليمين الى اليسار

+
new …
18{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment", 1)}} إضافة بعد إعادة النتيجة n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement", 1)}} طرح بعد إعادة النتيجة… --
17Logical NOT نفي منطقي +

right-to-left

+ +

من اليمين الى اليسار

+
! …
Bitwise NOT نفي بالبت~ …
Unary Plus + أحادي+ …
Unary Negation - أحادي- …
Prefix Increment إضافة قبل إعادة النتيجة++ …
Prefix Decrement طرح قبل إعادة النتيجة-- …
{{jsxref("Operators/typeof", "typeof")}} نوع الtypeof …
{{jsxref("Operators/void", "void")}} مجموعة خاليةvoid …
{{jsxref("Operators/delete", "delete")}} حذفdelete …
{{jsxref("Operators/await", "await")}} انتظارawait …
16Exponentiation أُس (الرفع الى قوة) +

right-to-left

+ +

من اليمين الى اليسار

+
… ** …
15Multiplication الضرب +

left-to-right

+ +

من اليسار الى اليمين

+
… * …
Division القسمة… / …
Remainder الباقي… % …
14Addition الجمع +

left-to-right

+ +

من اليسار الى اليمين

+
… + …
Subtraction الطرح… - …
13Bitwise Left Shift إزاحة لليسار بالبت +

left-to-right

+ +

من اليسار الى اليمين

+
… << …
Bitwise Right Shift إزاحة لليمين بالبت… >> …
Bitwise Unsigned Right Shift… >>> …
12Less Than أصغر من +

left-to-right

+ +

من اليسار الى اليمين

+
… < …
Less Than Or Equal أصغر من أو يساوي… <= …
Greater Than أكبر من… > …
Greater Than Or Equal أكبر من أو يساوي… >= …
{{jsxref("Operators/in", "in")}} في… in …
{{jsxref("Operators/instanceof", "instanceof")}} مشتق من … instanceof …
11Equality يساوي +

left-to-right

+ +

من اليسار الى اليمين

+
… == …
Inequality لا يساوي… != …
Strict Equality مساواة قطعية… === …
Strict Inequality لا يساوي قطعيا… !== …
10Bitwise AND و بالبت +

left-to-right

+ +

من اليسار الى اليمين

+
… & …
9Bitwise XOR  +

left-to-right

+ +

من اليسار الى اليمين

+
… ^ …
8Bitwise OR أو بالبت +

left-to-right

+ +

من اليسار الى اليمين

+
… | …
7Nullish coalescing operator +

left-to-right

+ +

من اليسار الى اليمين

+
… ?? …
6Logical AND و المنطقية +

left-to-right

+ +

من اليسار الى اليمين

+
… && …
5Logical OR أو المنطقية +

left-to-right

+ +

من اليسار الى اليمين

+
… || …
4Conditional الشرطية +

right-to-left

+ +

من اليمين الى اليسار

+
… ? … : …
3Assignment التعيين +

right-to-left

+ +

من اليمين الى اليسار

+
… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}} +

right-to-left

+ +

من اليمين الى اليسار

+
yield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1Comma / Sequence فاصلة / تسلسل +

left-to-right

+ +

من اليسار الى اليمين

+
… , …
diff --git a/files/ar/web/javascript/reference/operators/this/index.html b/files/ar/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..4e86b7e937 --- /dev/null +++ b/files/ar/web/javascript/reference/operators/this/index.html @@ -0,0 +1,381 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operators/this +translation_of: Web/JavaScript/Reference/Operators/this +--- +
{{jsSidebar ("عوامل التشغيل")}}
+ +

A الدالة thisالكلمة تتصرف بشكل مختلف قليلا في جافا سكريبت بالمقارنة مع اللغات الأخرى. كما أن لديها بعض الاختلافات بين الوضع الصارم والوضع غير الصارم.

+ +

في معظم الحالات ، thisيتم تحديد القيمة من خلال كيفية استدعاء دالة (ربط وقت التشغيل). لا يمكن تعيينه عن طريق التعيين أثناء التنفيذ ، وقد يكون مختلفًا في كل مرة يتم استدعاء الوظيفة. قدم ES5 طريقة {{jsxref ("Function.prototype.bind ()"، "bind ()")}} إلى {{jsxref ('Operators / this'، ") تعيين قيمة الوظيفة thisبغض النظر عن كيفية تسميتها" قدم كل من "The_bind_method" و 1)}} و ES2015 دالات الأسهم التي لا توفر ربطًا خاصًا بها this(فهي تحتفظ thisبقيمة السياق المعجم المرفق).

+ +
{{EmbedInteractiveExample ("pages / js / expressions-this.html")}}
+ + + +

بناء الجملة

+ +
هذه
+ +

القيمة

+ +

خاصية سياق التنفيذ (عام ، أو وظيفة ، أو تقييم) التي ، في الوضع غير الصارم ، تكون دائمًا مرجعًا إلى كائن وفي الوضع الصارم يمكن أن تكون أي قيمة.

+ +

السياق العالمي

+ +

في سياق التنفيذ العام (خارج أي وظيفة) ، thisيشير إلى الكائن العام سواء في الوضع الصارم أم لا.

+ +
// في متصفحات الويب ، يكون كائن النافذة أيضًا هو الكائن العام:
+console.log (هذه النافذة ===) ؛ // صحيح
+
+أ = 37 ؛
+console.log (window.a) ؛ // 37
+
+this.b = "MDN" ؛
+console.log (window.b) // "MDN"
+console.log (ب) // "MDN"
+
+ +
+

ملاحظة: يمكنك دائمًا الحصول بسهولة على الكائن العام باستخدام خاصية {{jsxref ("globalThis")}} العمومية ، بغض النظر عن السياق الحالي الذي تعمل فيه التعليمات البرمجية الخاصة بك.

+
+ +

سياق الوظيفة

+ +

داخل الدالة ، thisتعتمد القيمة على كيفية استدعاء الوظيفة.

+ +

مكالمة بسيطة

+ +

نظرًا لأن الشفرة التالية ليست في وضع صارم ، ولأن القيمة thisلم يتم تعيينها بواسطة المكالمة ، thisفسيتم تعيينها افتراضيًا على الكائن العام ، وهو {{domxref ("Window"، "window")}} في المتصفح.

+ +
الدالة f1 () {
+  أعد هذا ؛
+}}
+
+// في متصفح:
+f1 () === نافذة ؛ // صحيح
+
+// في العقدة:
+f1 () === عام ؛ // صحيح
+ +

ومع ذلك ، في الوضع الصارم ، إذا thisلم يتم تعيين القيمة عند إدخال سياق التنفيذ ، فإنها تظل كما undefinedهو موضح في المثال التالي:

+ +
الدالة f2 () {
+  "استخدام صارم" ؛ // انظر الوضع الصارم
+  أعد هذا ؛
+}}
+
+f2 () === غير معرّف ؛ // صحيح
+
+ +
في المثال الثاني ، thisيجب أن يكون {{jsxref ("undefined")}} ، لأنه f2تم استدعاؤه مباشرةً وليس كطريقة أو خاصية لكائن (مثل window.f2()). لم يتم تنفيذ هذه الميزة في بعض المتصفحات عندما بدأوا في دعم الوضع الصارم لأول مرة . ونتيجة لذلك ، أعادوا windowالكائن بشكل غير صحيح .
+ +

لتعيين قيمة thisإلى قيمة معينة عند استدعاء دالة ، استخدم {{jsxref ("Function.prototype.call ()" أو "call ()")}} أو {{jsxref ("Function.prototype.apply ( ) "،" Apply () ")}} كما في الأمثلة التالية.

+ +

مثال 1

+ +
// يمكن تمرير كائن باعتباره الوسيطة الأولى للاتصال أو التطبيق وهذا سوف يرتبط به.
+var obj = {a: 'Custom'} ؛
+
+// تم تعيين هذه الخاصية على الكائن العام
+var a = 'Global'؛
+
+الدالة whatsThis () {
+  أعد هذا. // تعتمد قيمة هذا على كيفية استدعاء الوظيفة
+}}
+
+ما هذا()؛ // "عالمي"
+whatsThis.call (obj) ؛ // 'مخصص'
+whatsThis.apply (obj) ؛ // 'مخصص'
+
+ +

مثال 2

+ +
إضافة دالة (ج ، د) {
+  إرجاع هذا. a + this.b + c + d ؛
+}}
+
+var o = {a: 1، b: 3} ؛
+
+// المعلمة الأولى هي الكائن المطلوب استخدامه كـ
+// 'this' ، يتم تمرير المعلمات اللاحقة كـ 
+// الوسيطات في استدعاء الوظيفة
+add.call (س ، 5 ، 7) ؛ // 16
+
+// المعلمة الأولى هي الكائن المطلوب استخدامه كـ
+// 'this' ، والثاني عبارة عن مصفوفة
+يتم استخدام // members كوسيطة في استدعاء دالة
+add.apply (س ، [10 ، 20]) ؛ // 34
+
+ +

علما بأن في الوضع غير صارمة، مع callو apply، إذا كانت القيمة التي تم تمريرها كما thisليست كائن، سيتم إجراء محاولة لتحويله إلى كائن باستخدام الداخلية ToObjectالعملية. لذا ، إذا كانت القيمة التي تم تمريرها بدائية مثل 7أو 'foo'، سيتم تحويلها إلى كائن باستخدام المُنشئ ذي الصلة ، لذلك 7يتم تحويل الرقم البدائي إلى كائن كما لو كان بواسطة new Number(7)والسلسلة 'foo'إلى كائن كما لو كان new String('foo')، على سبيل المثال

+ +
شريط الوظائف () {
+  console.log (Object.prototype.toString.call (this)) ؛
+}}
+
+bar.call (7) ؛ // [رقم الكائن]
+bar.call ('foo') ؛ // [سلسلة الكائن]
+
+ +

على bindطريقة

+ +

قدم ECMAScript 5 {{jsxref ("Function.prototype.bind ()")}}}. f.bind(someObject)يؤدي الاستدعاء إلى إنشاء وظيفة جديدة بنفس الجسم والنطاق f، ولكن thisفي حالة حدوثها في الوظيفة الأصلية ، في الوظيفة الجديدة ، يتم ربطها بشكل دائم بالحجة الأولى bind، بغض النظر عن كيفية استخدام الوظيفة.

+ +
دالة f () {
+  أعد هذا.
+}}
+
+var g = f.bind ({a: 'azerty'}) ؛
+console.log (g ()) ؛ // azerty
+
+var h = g.bind ({a: 'yoo'}) ؛ // bind يعمل مرة واحدة فقط!
+console.log (h ()) ؛ // azerty
+
+var o = {a: 37، f: f، g: g، h: h} ؛
+console.log (oa، of ()، og ()، oh ())؛ // 37،37، azerty، azerty
+
+ +

وظائف السهم

+ +

في دوال السهم ، thisيحتفظ بقيمة السياق المعجم المتضمن this. في الكود العام ، سيتم تعيينه على الكائن العام:

+ +
var globalObject = هذا ؛
+var foo = (() => this) ؛
+console.log (foo () === globalObject) ؛ // صحيح
+ +
+

ملاحظة: إذا thisتم تمرير الوسيطة إلى call، bindأو applyعند استدعاء وظيفة السهم ، فسيتم تجاهلها. لا يزال بإمكانك إضافة وسيطات إلى المكالمة ، ولكن thisArgيجب ضبط الوسيطة الأولى ( ) على null.

+
+ +
// Call كطريقة لكائن
+var obj = {func: foo} ؛
+console.log (obj.func () === globalObject) ؛ // صحيح
+
+// محاولة تعيين هذا باستخدام المكالمة
+console.log (foo.call (obj) === globalObject) ؛ // صحيح
+
+// جرت محاولة ضبط ذلك باستخدام الربط
+foo = foo.bind (obj) ؛
+console.log (foo () === globalObject) ؛ // صحيح
+ +

مهما كانت، fooالصورة thisيتم تعيين إلى ما كانت عليه عندما تم إنشاؤه (في المثال أعلاه، الكائن العالمي). وينطبق الشيء نفسه على دالات الأسهم التي تم إنشاؤها داخل دوال أخرى: thisبقايا تلك السياق المعجمية المرفقة.

+ +
// إنشاء كائن بشريط أسلوب يقوم بإرجاع دالة
+// يعيد هذا. يتم إنشاء الدالة التي تم إرجاعها كـ
+// دالة سهم ، لذا فهي مرتبطة بشكل دائم بـ
+// هذه الدالة المرفقة. يمكن تعيين قيمة الشريط
+// في المكالمة ، والتي تحدد بدورها قيمة 
+// عادت الدالة.
+var obj = {
+  شريط: الوظيفة () {
+    var x = (() => this) ؛
+    العودة س ؛
+  }}
+} ؛
+
+// Call bar كطريقة للهدف ، وضبط هذا الأمر على obj
+// تعيين مرجع للدالة التي تم إرجاعها إلى fn
+var fn = obj.bar () ،
+
+// Call fn دون تعيين هذا ، سيكون الوضع الافتراضي عادةً
+// إلى الكائن العام أو غير محدد في الوضع الصارم
+console.log (fn () === obj) ؛ // صحيح
+
+// لكن احذر إذا رجعت إلى طريقة الكائن بدون تسميتها
+var fn2 = obj.bar ،
+// استدعاء وظيفة السهم هذا من داخل طريقة الشريط ()
+// سيعود الآن النافذة ، لأنه يتبع هذا من fn2.
+console.log (fn2 () () == window) ؛ // صحيح
+
+ +

في أعلاه ، تم تعيين الوظيفة (يطلق عليها الوظيفة المجهولة أ) obj.barلإرجاع وظيفة أخرى (يطلق عليها الوظيفة المجهولة ب) التي تم إنشاؤها كدالة سهم. ونتيجة لذلك، وظيفة B في thisتعيين دائم لل thisمن obj.bar(وظيفة A) عندما دعا. عندما يتم استدعاء الدالة التي تم إرجاعها (الوظيفة B) ، thisستكون دائمًا ما تم تعيينها عليه في البداية. في المثال رمز أعلاه، وظيفة باء thisمن المقرر أن وظيفة A و thisالذي هو obj، لذلك لا يزال المقرر أن objحتى عندما دعا بطريقة من شأنها أن تحدد عادة في thisل undefinedأو الكائن العالمي (أو أي طريقة أخرى كما في المثال السابق في عالمي سياق التنفيذ).

+ +

كطريقة كائن

+ +

عندما يتم استدعاء دالة كطريقة لكائن ما ، thisيتم تعيينها على الكائن الذي يتم استدعاء الطريقة.

+ +

في المثال التالي ، عندما o.f()يتم استدعاء ، داخل الوظيفة thisمنضمة إلى oالكائن.

+ +
var o = {
+  الدعامة: 37 ،
+  و: الوظيفة () {
+    أعد هذا. prop؛
+  }}
+} ؛
+
+console.log (من ()) ؛ // 37
+
+ +

لاحظ أن هذا السلوك لا يتأثر على الإطلاق بكيفية أو مكان تعريف الوظيفة. في المثال السابق ، قمنا بتعريف الوظيفة المضمنة fكعضو أثناء تعريف o. ومع ذلك ، كان بإمكاننا تحديد الوظيفة بسهولة ثم إرفاقها بها لاحقًا o.f. يؤدي القيام بذلك إلى نفس السلوك:

+ +
var o = {prop: 37} ؛
+
+وظيفة مستقلة () {
+  أعد هذا. prop؛
+}}
+
+of = مستقل ؛
+
+console.log (من ()) ؛ // 37
+
+ +

يوضح هذا أنه من المهم فقط أن يتم استدعاء الوظيفة من fعضو o.

+ +

وبالمثل ، thisلا يتأثر الربط إلا بمرجع العضو المباشر. في المثال التالي ، عندما نستدعي الوظيفة ، نسميها كطريقة gللكائن o.b. هذه المرة أثناء التنفيذ ، thisسيتم الرجوع إلى داخل الوظيفة o.b. حقيقة أن الكائن هو نفسه عضو oليس له أي عواقب ؛ المرجع الأكثر فورية هو كل ما يهم.

+ +
ob = {g: Independent، prop: 42} ؛
+console.log (obg ()) ؛ // 42
+
+ +

this في سلسلة النموذج الأولي للكائن

+ +

ينطبق نفس المفهوم على الأساليب المحددة في مكان ما على سلسلة النموذج الأولي للكائن. إذا كانت الطريقة موجودة في سلسلة نموذجية للكائن ، thisفيشير إلى الكائن الذي تم استدعاء الطريقة ، كما لو كانت الطريقة موجودة على الكائن.

+ +
var o = {f: function () {return this.a + this.b؛ }} ؛
+var p = Object.create (o) ؛
+السلطة الفلسطينية = 1 ؛
+pb = 4 ؛
+
+console.log (pf ()) ؛ // 5
+
+ +

في هذا المثال ، الكائن الذي تم تعيينه للمتغير pليس له fخاصية خاصة به ، بل يرثه من النموذج الأولي الخاص به. ولكن لا يهم أن fيجد البحث في النهاية عضوًا يحمل هذا الاسم o؛ بدأ البحث كمرجع إلى p.f، لذا thisداخل الوظيفة تأخذ قيمة الكائن المشار إليه باسم p. هذا ، حيث fيطلق عليه أسلوبًا p، thisيشير إليه p. هذه ميزة مثيرة للاهتمام في وراثة النموذج الأولي لجافا سكريبت.

+ +

this مع مُدرب أو مُدرب

+ +

مرة أخرى ، نفس الفكرة صحيحة عندما يتم استدعاء دالة من getter أو setter. this ترتبط الوظيفة المستخدمة كجلب أو أداة ضبط بالكائن الذي يتم تعيين الخاصية أو الحصول عليها منه.

+ +
الدالة () {
+  إرجاع this.a + this.b + this.c ؛
+}}
+
+var o = {
+  أ: 1 ،
+  ب: 2 ،
+  ج: 3 ،
+  الحصول على المتوسط ​​() {
+    العودة (this.a + this.b + this.c) / 3 ؛
+  }}
+} ؛
+
+Object.defineProperty (o، 'sum'، {
+    get: sum، enumerable: true، configurable: true})؛
+
+console.log (o. avage، o.sum) ؛ // 2 ، 6
+
+ +

كمنشئ

+ +

عند استخدام دالة كمنشئ (باستخدام الكلمة الرئيسية {{jsxref ("Operators / new"، "new")}}) ، thisفإنها مرتبطة بالعنصر الجديد الذي يتم إنشاؤه.

+ +
+

على الرغم من أن الإعداد الافتراضي للمنشئ هو إرجاع الكائن المشار إليه this، فإنه يمكنه بدلاً من ذلك إرجاع كائن آخر (إذا لم تكن القيمة المرجعة كائنًا ، فسيتم thisإرجاع الكائن).

+
+ +
/ *
+ * يعمل المنشئ على النحو التالي:
+ *
+ * وظيفة MyConstructor () {
+ * // كود الجسم للوظيفة الفعلية يظهر هنا.  
+ * // إنشاء خصائص على | هذا | مثل
+ * // مرغوب من خلال التنازل عنها. على سبيل المثال ،
+ * this.fum = "nom" ؛
+ * // إلى آخره...
+ *
+ * // إذا كانت الوظيفة تحتوي على بيان إرجاع ذلك
+ * // يقوم بإرجاع كائن ، سيكون هذا الكائن هو
+ * // نتيجة | جديد | التعبير. غير ذلك،
+ * // نتيجة التعبير هي الكائن
+ * // مرتبط حاليًا بـ | this |
+ * // (أي الحالة الشائعة التي تُرى عادةً).
+ *}
+ * /
+
+الدالة C () {
+  this.a = 37 ؛
+}}
+
+var o = new C () ،
+Console.log (oa) ؛ // 37
+
+
+الدالة C2 () {
+  this.a = 37 ؛
+  العودة {أ: 38} ؛
+}}
+
+o = C2 () جديد ؛
+Console.log (oa) ؛ // 38
+
+ +

في المثال الأخير ( C2) ، لأنه تم إرجاع كائن أثناء البناء ، thisيتم التخلص من الكائن الجديد الذي كان مرتبطًا به ببساطة. (هذا يجعل العبارة " this.a = 37;" رمزًا ميتًا بشكل أساسي . ليس ميتًا تمامًا لأنه يتم تنفيذه ، ولكن يمكن إزالته بدون أي تأثيرات خارجية.)

+ +

كمعالج حدث DOM

+ +

عند استخدام دالة كمعالج للأحداث ، thisيتم تعيينها على العنصر الذي يتم وضع المستمع عليه (بعض المتصفحات لا تتبع هذا الاصطلاح للمستمعين المضافين ديناميكيًا بأساليب أخرى غير {{domxref ("EventTarget / addEventListener"، "addEventListener" () ")}}).

+ +
// عند الاتصال كمستمع ، يحول العنصر ذي الصلة إلى اللون الأزرق
+دالة bluify (e) {
+  // دائما صحيح او صادق
+  console.log (هذا === e.currentTarget) ؛
+  // true عندما يكون currentTarget والهدف هما نفس الكائن
+  console.log (هذا === e.target) ؛
+  this.style.backgroundColor = '# A5D9F3' ؛
+}}
+
+// احصل على قائمة بكل عنصر في المستند
+var Elements = document.getElementsByTagName ('*') ؛
+
+// أضف bluify كمستمع فوق حتى عندما
+تم النقر على عنصر // ، ويتحول إلى اللون الأزرق
+for (var i = 0؛ i <element.length؛ i ++) {
+  العناصر [i] .addEventListener ('click'، bluify، false) ؛
+}}
+ +

في معالج حدث مضمن

+ +

عندما يتم استدعاء الرمز من معالج مضمّن في الحدث ، thisيتم تعيينه على عنصر DOM الذي يتم وضع المستمع عليه:

+ +
<button onclick = "alert (this.tagName.toLowerCase ())؛">
+  تظهر هذه
+</button>
+
+ +

يظهر التنبيه أعلاه button. لاحظ أن الكود الخارجي فقط هو الذي تم thisضبطه بهذه الطريقة:

+ +
<button onclick = "alert ((function () {return this؛}) ())؛">
+  أظهر هذا الداخلية
+</button>
+
+ +

في هذه الحالة ، thisلم يتم تعيين الوظيفة الداخلية ، لذا فإنها تُرجع الكائن العام / النافذة (أي الكائن الافتراضي في الوضع غير الصارم حيث thisلا يتم تعيينه بواسطة المكالمة).

+ +

مواصفات

+ + + + + + + + + + + + +
تخصيص
{{SpecName ('ESDraft'، '# sec-this-keyword'، 'The this keyword')}}
+ +

التوافق المتصفح

+ + + +

{{Compat ("javascript.operators.this")}}

+ +

أنظر أيضا

+ + diff --git a/files/ar/web/javascript/reference/statements/index.html b/files/ar/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..b9fd7f94a0 --- /dev/null +++ b/files/ar/web/javascript/reference/statements/index.html @@ -0,0 +1,141 @@ +--- +title: Statements and declarations +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

+ +

Statements and declarations by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Control flow

+ +
+
{{jsxref("Statements/block", "Block")}}
+
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
+
{{jsxref("Statements/break", "break")}}
+
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
+
{{jsxref("Statements/continue", "continue")}}
+
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
+
{{jsxref("Statements/Empty", "Empty")}}
+
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
+
{{jsxref("Statements/if...else", "if...else")}}
+
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
+
{{jsxref("Statements/switch", "switch")}}
+
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
+
{{jsxref("Statements/throw", "throw")}}
+
Throws a user-defined exception.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
Marks a block of statements to try, and specifies a response, should an exception be thrown.
+
+ +

Declarations

+ +
+
{{jsxref("Statements/var", "var")}}
+
Declares a variable, optionally initializing it to a value.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Functions and classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declares a function with the specified parameters.
+
{{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declares a class.
+
+ +

Iterations

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
+
{{jsxref("Statements/for", "for")}}
+
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
+
{{jsxref("Statements/for...in", "for...in")}}
+
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
+
{{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+
{{jsxref("Statements/while", "while")}}
+
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
+
+ +

Others

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + diff --git a/files/ar/web/javascript/reference/statements/return/index.html b/files/ar/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..191ab5296c --- /dev/null +++ b/files/ar/web/javascript/reference/statements/return/index.html @@ -0,0 +1,145 @@ +--- +title: return +slug: Web/JavaScript/Reference/Statements/return +translation_of: Web/JavaScript/Reference/Statements/return +--- +
{{jsSidebar("Statements")}}
+ +

ال return ينهي البيان تنفيذ الوظيفة ويحدد قيمة ليتم ارجاعها الى دالة الاستدعاء

+ +
{{EmbedInteractiveExample("pages/js/statement-return.html")}}
+ + + +

بناء الجملة

+ +
return [expression]; 
+ +
+
expression
+
التعبير المراد استرجاع قيمتة. اذا تم حذفه, فسيتم ارجاع undefined بدلاً من ذالك
+
+ +

الوصف

+ +

عند استخدام عبارة return في جسم الدالة,يتم ايقاف تنفيذ الوظيفة.اذا تم تحديد ذالك,يتم ارجاع قيمة معينة الى دالة الاستدعاء.على سبيل المثال,تعرض الدالة التالية مربع سعتها , x,حيث x هي رقم.

+ +
function square(x) {
+   return x * x;
+}
+var demo = square(3);
+// demo will equal 9
+
+ +

اذا تم حذف القيمة,يتم ارجاع undefined بدلاُ من ذالك

+ +

تعطل عبارات الارجاع التالية تنفيذ الوظيفة

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

الادراج التلقائي للفاصلة المنقوطة (Semicolon)

+ +

تتاثر عبارة الارجاع بادراج الفاصلة المنقوطة تلقائياُُ (ASI) .

+ +

لا يُسمح بفاصل سطر بين الكلمة الاساسية return  و التعبير

+ +
return
+a + b;
+
+ +

is transformed by ASI into:

+ +
return;
+a + b;
+
+ +

The console will warn "unreachable code after return statement".

+ +
Starting with Firefox 40, a warning is shown in the console if unreachable code is found after a return statement.
+ +

To avoid this problem (to prevent ASI), you could use parentheses:

+ +
return (
+  a + b
+);
+
+ +

Examples

+ +

Interrupt a function

+ +

A function immediately stops at the point where return is called.

+ +
function counter() {
+  for (var count = 1; ; count++) {  // infinite loop
+    console.log(count + 'A'); // until 5
+      if (count === 5) {
+        return;
+      }
+      console.log(count + 'B');  // until 4
+    }
+  console.log(count + 'C');  // never appears
+}
+
+counter();
+
+// Output:
+// 1A
+// 1B
+// 2A
+// 2B
+// 3A
+// 3B
+// 4A
+// 4B
+// 5A
+
+ +

Returning a function

+ +

See also the article about Closures.

+ +
function magic() {
+  return function calc(x) { return x * 42; };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.return")}}

+ +

See also

+ + + +
+
+
diff --git "a/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/get/index.html" "b/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/get/index.html" new file mode 100644 index 0000000000..d3789ba7bd --- /dev/null +++ "b/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/get/index.html" @@ -0,0 +1,165 @@ +--- +title: getter +slug: Web/JavaScript/Reference/الدوال/get +translation_of: Web/JavaScript/Reference/Functions/get +--- +
{{jsSidebar("Functions")}}
+ +

The get صينطاكس طعمنيققbinds an object property to a function that will be called when that property is looked up.

+ +
{{EmbedInteractiveExample("pages/js/functions-getter.html")}}
+ + + +

Syntax

+ +
{get prop() { ... } }
+{get [expression]() { ... } }
+ +

Parameters

+ +
+
prop
+
rty to bind to the given fun-tion.
+
expression
+
Starting with ECMAScript 2015, you can also use expressions for a computed property name to bind to the given function.
+
+ +

Description

+ +

احا الشبشب ضاع احا دا كان ةبصباع

+ +

It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.

+ +

Note the following when working with the get syntax:

+ + + +

Examples

+ +

Defining a getter on new objects in object initializers

+ +

This will create a pseudo-property latest for object obj, which will return the last array item in log.

+ +
const obj = {
+  log: ['example','test'],
+  get latest() {
+    if (this.log.length === 0) return undefined;
+    return this.log[this.log.length - 1];
+  }
+}
+console.log(obj.latest); // "test"
+
+ +

Note that attempting to assign a value to latest will not change it.

+ +

Deleting a getter using the delete operator

+ +

If you want to remove the getter, you can just {{jsxref("Operators/delete", "delete")}} it:

+ +
delete obj.latest;
+
+ +

Defining a getter on existing objects using defineProperty

+ +

To append a getter to an existing object later at any time, use {{jsxref("Object.defineProperty()")}}.

+ +
const o = {a: 0};
+
+Object.defineProperty(o, 'b', { get: function() { return this.a + 1; } });
+
+console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
+ +

Using a computed property name

+ +
const expr = 'foo';
+
+const obj = {
+  get [expr]() { return 'bar'; }
+};
+
+console.log(obj.foo); // "bar"
+ +

Smart / self-overwriting / lazy getters

+ +

Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed. If it is never needed, you never pay the cost.

+ +

An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are smart (or "memoized") getters. The value is calculated the first time the getter is called, and is then cached so subsequent accesses return the cached value without recalculating it. This is useful in the following situations:

+ + + +
+

This means that you shouldn’t write a lazy getter for a property whose value you expect to change, because if the getter is lazy then it will not recalculate the value.

+ +

Note that getters are not “lazy” or “memozied” by nature; you must implement this technique if you desire this behavior.

+
+ +

In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value getsreturn this.notifier = document.getElementById('bookmarked-notification-anchor'); },

+ +

For Firefox code, see also the XPCOMUtils.jsm code module, which defines the defineLazyGetter() function.

+ +

get vs. defineProperty

+ +

While using the get keyword and {{jsxref("Object.defineProperty()")}} have similar results, there is a subtle difference between the two when used on {{jsxref("classes")}}.

+ +

When using get the property will be defined on the instance's prototype, while using {{jsxref("Object.defineProperty()")}} the property will be defined on the instance it is applied to.

+ +
class Example {
+  get hello() {
+    return 'world';
+  }
+}
+
+const obj = new Example();
+console.log(obj.hello);
+// "world"
+
+console.log(Object.getOwnPropertyDescriptor(obj, 'hello'));
+// undefined
+
+console.log(
+  Object.getOwnPropertyDescriptor(
+    Object.getPrototypeOf(obj), 'hello'
+  )
+);
+// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.functions.get")}}

+ +

See also

+ + diff --git "a/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" "b/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" new file mode 100644 index 0000000000..368d8af03d --- /dev/null +++ "b/files/ar/web/javascript/reference/\330\247\331\204\330\257\331\210\330\247\331\204/index.html" @@ -0,0 +1,645 @@ +--- +title: الدوال +slug: Web/JavaScript/Reference/الدوال +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Description

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

Functions are not the same as procedures. A function always returns a value, whereas a procedure might not.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+   theObject.brand = "Toyota";
+ }
+
+ /*
+  * Declare variable 'mycar';
+  * create and initialize a new Object;
+  * assign reference to it to 'mycar'
+  */
+ var mycar = {
+   brand: "Honda",
+   model: "Accord",
+   year: 1998
+ };
+
+ /* Logs 'Honda' */
+ console.log(mycar.brand);
+
+ /* Pass object reference to the function */
+ myFunc(mycar);
+
+ /*
+  * Logs 'Toyota' as the value of the 'brand' property
+  * of the object, as changed to by the function.
+  */
+ console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Defining functions

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details):

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function declaration (function* statement)

+ +
+

Note: Generator functions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +
+

Note: Generator functions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +
+

Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function parameters

+ +
+

Note: Default and rest parameters are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

Default parameters

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Rest parameters

+ +

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

The arguments object

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Defining method functions

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +
+

Note: Method definitions are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.

+
+ +

Starting with ECMAScript 6, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Function constructor vs. function declaration vs. function expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
function multiply(x, y) {
+   return x * y;
+}
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x == 0) {            // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y == 10) {     // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Block-level functions

+ +

In strict mode, starting with ES2015 (ES6), functions inside blocks are now scoped to that block. Prior to ES6, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (0) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Examples

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is peformed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

+ +
 if ('function' == typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatNo}}{{CompatGeckoDesktop("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Block-level functions{{CompatUnknown}}{{CompatGeckoDesktop("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions{{CompatUnknown}}39{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Block-level functions{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf