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

Asked

Viewed 264 times

4

  • What’s the difference between Lexical Scope and Dynamic Scope?

  • What are the advantages of using each of them?

  • When they should be used?

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, as internal functions (within their scope) have access to external function variables, fun2() can access the declared variable x in the parent role fun().

Dynamic Escoping:

Few languages offer dynamic scope and Javascript is not included in this group. An example is the first implementation of Lisp, in the 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 in whatever function they call fun with x stated in 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 outer scope is dynamic and depends on the string call of the functions.

The dynamic scope is like passing references of all variables to the called function.

An example of why the compiler cannot 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 runtime condition. If true, the call chain is similar to:

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

dummy2 --> fun()

The external scope of fun in both cases is the caller plus the caller of the caller and so on .

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

Source: - What is lexical Scope?

- Lexical scoping

Browser other questions tagged

You are not signed in. Login or sign up in order to post.