--- title: var slug: Web/JavaScript/Reference/Statements/var tags: - hoisted - הכרזה - משתנה translation_of: Web/JavaScript/Reference/Statements/var ---
מילת ההצהרה var
משמשת להכזרה על משתנה.
var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]];
varnameN
valueN
בשפת ג'אווה סקריפט אנו משתמשים במשתנים על מנת להחזיק ערכים שונים.
הקצאת ערך למשתנה ללא הצהרה מראש הופכת אותו למשתנה כגלובלי.
ניתן להשתמש במשתנה לפני שהוכרז, השימוש יעשה באמצעות Hoisting.
מהם ההבדלים בין משתנים מוצהרים לאלה שאינם?
1. ראשית, משתנים מוצהרים יעשו רק את הפעולה שלשמה נוצרו, לעומת משתנים לא מוצהרים הנחשבים גלובלים.
function x() { y = 1; // Throws a ReferenceError in strict mode var z = 2; } x(); console.log(y); // logs "1" console.log(z); // Throws a ReferenceError: z is not defined outside x
2. משתנים מוצהרים מוכרזים לפני ביצוע קוד כלשהו לעומת זאת משתנים לא מוצהרים אינם קיימים עד שהקוד שמכריז עליהם מתבצע.
console.log(a); // Throws a ReferenceError. console.log('still going...'); // Never executes.
var a; console.log(a); // logs "undefined" or "" depending on browser. console.log('still going...'); // logs "still going...".
בשל שני ההבדלים הללו, אי הכרזה על משתנים עשויה להוביל לשגיאות בלתי צפויות.
לכן, מומלץ תמיד להכריז על משתנים, גם אם הם נמצאים בפונקציה.
זוהי התנהגות ברירת המחדל של השפה, שתפקידה להעביר את כל ההצהרות לחלק העליון של הסקריפט או הפונקציה ולכן משמעות הדבר היא שניתן להשתמש במשתנה לפני שהוכרז.
bla = 2; var bla; // ... // is implicitly understood as: var bla; bla = 2;
מומלץ להצהיר על משתנים בחלקו העליון של הסקריפט או הפונקציה וכך יהיה ברור אילו משתנים שייכים לפונקציה באופן מקומי ואילו גלובלים.
חשוב לזכור ששימוש ב-Hoisting ישפיע על הצהרת המשתנה אך לא על אתחול הערך:
function do_something() { console.log(bar); // undefined var bar = 111; console.log(bar); // 111 } // is implicitly understood as: function do_something() { var bar; console.log(bar); // undefined bar = 111; console.log(bar); // 111 }
var a = 0, b = 0;
var a = 'A'; var b = a; // Equivalent to: var a, b = a = 'A';
var x = 0; function f() { var x = y = 1; // x is declared locally. y is not! } f(); console.log(x, y); // Throws a ReferenceError in strict mode (y is not defined). 0, 1 otherwise. // In non-strict mode: // x is the global one as expected // y leaked outside of the function, though!
Specification | Status | Comment |
---|---|---|
{{SpecName('ES1')}} | {{Spec2('ES1')}} | Initial definition. Implemented in JavaScript 1.0 |
{{SpecName('ES5.1', '#sec-12.2', 'var statement')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-variable-statement', 'variable statement')}} | {{Spec2('ES6')}} | |
{{SpecName('ESDraft', '#sec-variable-statement', 'variable statement')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.statements.var")}}