What is the difference between Lexical Scope and Dynamic Scope in Javascript?

4
  • What is the difference between Lexical Scope and Dynamic Scope ?

  • What are the advantages of using each of them?

  • When should they be used?

asked by anonymous 30.03.2017 / 15:27

1 answer

4

Lexical Scoping (also called static scoping).

window.onload = function fun() {
    var x = 5;
    function fun2() {
       console.log(x);
    }
    fun2();
};

fun2 is an internal function that is defined within fun() and is available within its scope. fun2 does not have its own local variables, however, because internal functions (within its scope) have access to external function variables, fun2() can access the declared variable x in the fun() parent function %.

Dynamic Escoping:

Few languages offer dynamic scope and Javascript is not included in this group. An example is the first implementation of Lisp , in C-like Syntax:

void fun()
{
    printf("%d", x);
}

void dummy1()
{
    int x = 5;

    fun();
}

void dummy2()
{
    int x = 10;

    fun();
}

fun can access x (variable) in dummy1 or dummy2 , or any x on any function that calls fun with x declared on it.

dummy1();
Irá imprimir 5

dummy2();
Irá imprimir 10

The first is called static because it can be deduced at compile time, the second is called dynamic because the external scope is dynamic and depends on the string call of the functions.

Dynamic scope is how to pass references of all variables to the called function.

An example of why the compiler can not deduce the external dynamic scope of a function, consider our last example if we write something like this:

if(condicao)
    dummy1();
else
    dummy2();

The call chain depends on a run-time condition. If true, the call string is similar to:

dummy1 --> fun()
Se a condição for falsa:

dummy2 --> fun()

The outer scope of fun in both cases is the caller plus the caller's caller, and so on.

OBS: C language does not allow nested functions or dynamic scope.

Source: - What is lexical scope?

- Lexical scoping

    
30.03.2017 / 15:42