يتم تحديد نطاق المتغيرات المعلنة باستخدام الكلمة الأساسية var إلى الوظيفة التي تم إنشاؤها فيها، أو إذا تم إنشاؤها خارج أي وظيفة، إلى الكائن العام. Let وconst عبارة عن نطاق كتلة، مما يعني أنه لا يمكن الوصول إليهما إلا من خلال أقرب مجموعة من الأقواس المتعرجة (وظيفة، أو كتلة if-else، أو for-loop).
function foo() { // All variables are accessible within functions. var bar = 'bar'; let baz = 'baz'; const qux = 'qux'; console.log(bar); // bar console.log(baz); // baz console.log(qux); // qux } console.log(bar); // ReferenceError: bar is not defined console.log(baz); // ReferenceError: baz is not defined console.log(qux); // ReferenceError: qux is not defined if (true) { var bar = 'bar'; let baz = 'baz'; const qux = 'qux'; } // var declared variables are accessible anywhere in the function scope. console.log(bar); // bar // let and const defined variables are not accessible outside the block they were defined in. console.log(baz); // ReferenceError: baz is not defined console.log(qux); // ReferenceError: qux is not defined
var يسمح برفع المتغيرات، مما يعني أنه يمكن الرجوع إليها في الكود قبل الإعلان عنها. لن يسمح Let وconst بهذا، بل سيتسببان في حدوث خطأ.
console.log(foo); // undefined var foo = 'foo'; console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization let baz = 'baz'; console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization const bar = 'bar';
إعادة الإعلان عن متغير باستخدام var لن يؤدي إلى حدوث خطأ، ولكن Let وconst سيؤديان إلى حدوث خطأ.
var foo = 'foo'; var foo = 'bar'; console.log(foo); // "bar" let baz = 'baz'; let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared
يختلف Let و const في أن Let يسمح بإعادة تعيين قيمة المتغير بينما لا يسمح const بذلك.
// This is fine. let foo = 'foo'; foo = 'bar'; // This causes an exception. const baz = 'baz'; baz = 'qux';
تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.
Copyright© 2022 湘ICP备2022001581号-3