Doubt about variable declaration

Asked

Viewed 29 times

1

Hello!

Before opening this question, I researched to see if there was any similar open, but I could not resolve my doubt. If there is one and you can provide me the link, thank you.

I don’t know much yet, I’m learning. At the moment, I am studying 'Browser Object Models' and a course I am doing and I have the following question:

What is the difference between this assignment/declaration:

function abrirPopUp() {
            janela = window.open('http://google.com', 'nova_janela', 'width=200, height=100');
        }

And this one down here?

 function abrirPopUp() {
                var janela = window.open('http://google.com', 'nova_janela', 'width=200, height=100');
            }

In the first form, everything happens as it should. In the second, however, I have no result. I will put all the code down here:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JavaScript</title>
        <script>

            function abrirPopUp() {
                var janela = window.open('http://google.com', 'nova_janela', 'width=200, height=100');
            }

            function fecharPopUp() {
                janela.close();
            }

        </script>
    </head>
    <body>
        <button onclick="abrirPopUp();">Abrir janela</button>
        <button onclick="fecharPopUp();">Fechar janela</button>
        <button onclick="window.print();">Imprimir Página</button>
    </body>
</html>

I tried to be as clear as I could.

From now on, thank you very much for the strength.

EDIT1: The problem happens when I use the close method of BOM. In the first statement, everything works normally. In the second, no.

  • Related: https://answall.com/q/47165/112052

1 answer

1


Good night, jezq!

I have no experience with Javascript, but as far as I know,

function abrirPopUp() {
   janela = ...;
}

The variable janela is global which means it is accessible anywhere in your code. Already at

function abrirPopUp() {
   var janela = ...;
}

The variable is local, meaning that it is accessible only within the function in which it was declared. So that the function responsible for the closure can access the variable, declare it globally.

  • Good evening, Ivan. Thank you so much for the answer! Nor has this concept of global and local... our!

  • I am happy to help you =) If possible, mark my answer as correct if your problem has actually been solved. Good evening

Browser other questions tagged

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