Scope of variables in Event Attributes

Asked

Viewed 70 times

-1

We know that when declaring a variable with var, it only loses the overall scope when declared within a function, for example:

function f(){
   var a = "string";
   console.log(a); // string
}

console.log(a); // a is not defined

Unlike let and const, which also have block scope:

for(var x=0; x<10; x++){}
console.log(x); // 10

for(let y=0; y<10; y++){}
console.log(y); // y is not defined

Well. Look at these two examples with and without var in the variable nome within the event attribute onclick:

1) With var:

function f(){
   console.log(nome);
}
<button onclick="var nome = 'Fulano'; console.log(nome); f()">Clique aqui</button>

2) Sem var:

function f(){
   console.log(nome);
}
<button onclick="nome = 'Fulano'; console.log(nome); f()">Clique aqui</button>

In the example 1 causes error in console.log(nome) of function f() because the variable nome has a restricted scope within the attribute onclick.

Already in this example below, where the variable nome is declared with var within a href with javascript:, the variable is global in scope:

<a href="javascript: var nome = 'Fulano';">Link</a>
console.log(nome); // Fulano

Like onclick and href are two very different attributes, it is understandable this behavior, but what I do not understand is why the variable var nome within the onclick have no global scope, since, in all the explanations I researched, the var has no block scope, only in functions.

If the content of onclick, in theory, it is just a common Javascript code, the variable var nome would not have to have global scope when declaring within Event Attributes, as in the example 1 above?

1 answer

2


Doing a little research, I realized that the attribute onclick is actually a function, that is, everything inside the attribute is inside a function onclick which is called at the click.

When checking the widget properties in the console button, function is displayed onclick with the content of the attribute:

inserir a descrição da imagem aqui

Like this, when using var, the variable loses the global scope because the attribute code is inserted in the event function.

In the case of href this does not happen because the href does not trigger an event function:

inserir a descrição da imagem aqui

Browser other questions tagged

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