Hoisting - Why are callback functions not hoisted in JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I understand the concept of variables and function declaration in JavaScript being hoisted at the top of the enclosing scope. But if I have a named callback function, its not being hoisted. I am not able to understand why is that so. I have the code in the below link explaining the scenario

Example:

function enclosingScope () {
  var b;

  function inner (def) {
    def();  
  }
  var a = 2;
}

// After hoisting due to compilation, the above changes to 
function enclosingScope () {
  // Function declarations are hoisted before variables
  function inner (def) {
    def(); 
  }

  var b, a;
  a = 2
}

// But if I have a named callback, will that be hoisted?
function enclosingScope () {
  function inner (def) {
    def();
  }

  var b, a;
  a = 2

  inner(function cb () {
    console.log( Test callback hoisting )
  })
}

Answers

The behavior in question is not limited to named callbacks. It s the way any named function expression works. Consider the following:

function foo() {
  (function baz() { });
  console.log(typeof baz);
}

> foo()
< undefined

baz is not accessible outside its body. So this is a different issue than hoisting.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/36660703/why-are-callback-functions-not-hoisted-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils