Hoisting

from Wikipedia, the free encyclopedia

With Hoisting (Engl., Hoisting) refers to the behavior of one JavaScript -Interpreters when declaring variables and functions in functions.

When the JavaScript interpreter encounters a function, it first checks in the entire function which variables are defined in the local scope of the function and which have been defined globally. If variable definitions with a local area of ​​validity are found, they are declared immediately, but not initialized. The JavaScript interpreter "pulls" all declarations of variables in the function body just below the head of the function ( hoisting ). However, the assignment only takes place at those points where the variables are defined.

var s = "hallo";    // globale Variable
function foo() {
    document.write(s);   // ergibt "undefined" und nicht "hallo"
    var s = "test";      // Initialisierung von 's'
    document.write(s);   // ergibt "test"
}
foo();

The code above is executed by the JavaScript interpreter as if the following had been defined:

var s = "hallo";    // globale Variable
function foo() {
    var s;               // Hoisting von s, das global definierte s wird damit überdeckt
    document.write(s);   // ergibt "undefined" - jetzt wird auch klar, warum!
    s = "test";          // Zuweisung
    document.write(s);   // ergibt "test"
}
foo();

The declaration of functions is also moved to the front, as the example below shows. The Javascript interpreter pushes the declaration and implementation (!) Of the function definition of foo to the very beginning, so that foo () can even be called! The declaration of bar is also moved to the beginning, but the implementation of the anonymous function is not . Therefore bar () throws an error.

document.write(typeof foo); // ergibt "function"
foo();                      // wird daher ausgeführt
document.write(typeof bar); // ergibt wieder "undefined" - siehe obiges Beispiel!
bar();                      // löst daher einen Fehler aus
function foo() {};          // Funktionsdefinition - Hoisting von Deklaration und Implementierung
var bar = function () {};   // literale Definition - nur Hoisting der Deklaration

This fact can be used when including sub-functions by defining them below the final return statement.

function f(x) {
  var y = foo(x);                 // Hoisting von foo
  return y;                       // abschließendes return
  function foo(z) {return z*z};   // Funktionsdefinition unterhalb von return
}

f(2);  // ergibt 4

Hoisting occurs not only within functions but also in a global context, but one should avoid the global definition of variables.

literature

  • Zachary Kessin: Programming HTML5 Applications Building Powerful Cross-platform Environments in JavaScript. O'Reilly Media Publisher, Sebastopol, CA 2011, ISBN 978-1-4493-9908-5 .

Individual evidence

  1. Handling of Javascript variables. at: heise.de , accessed on December 20, 2012.