-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?