JavaScript variables and properties

In JavaScript, a global variable is also a property of an object window. What about local variables? Are they the property of any property?

For example:

var apple=3;
alert(apple);                   //  3
alert(window.apple);            //  same

thing();

function thing() {
    var banana=4;
    alert(banana);              //  4
    alert(thing.banana);        //  doesn’t work, of course
}

Is a bananaproperty of any object

+4
source share
3 answers

What about local variables? Are they the property of any property?

No. When execution enters a function, a new declarative environment record is created to store identifiers .

( with ), , .

. ?

+6

. , -, static , C/++. :

function thing() {
    thing.banana = (thing.banana + 1) || 1;
    alert('This function was ran '+ thing.banana + ' times.');
}

thing(); // alerts "This function was ran 1 times"
thing(); // alerts "This function was ran 2 times"
thing(); // alerts "This function was ran 3 times"
thing(); // alerts "This function was ran 4 times"
thing(); // alerts "This function was ran 5 times"
alert(thing.banana) // alerts 5
+2

scope , . .

<!DOCTYPE html>
<html>
<body>

<p>
In HTML, all global variables will become window variables.
</p>

<p id="demo"></p>

<script>
var apple=3;
var obj=new thing();
document.getElementById("demo").innerHTML =
"I can display " + window.apple + " and " + window.banana + " but not local " + window.orange + ". I can call this from getter though " + obj.getOrange();


function thing() {
    banana=4;
    var orange=5;

    this.getOrange = function(){
        return orange;
    }

}
</script>

</body>
</html>

.

In HTML, all global variables will become window variables.

I can display 3 and 4 but not local undefined. I can call this from getter though 5

Therefore, unless you create getter and setter for local variables, you cannot reference them. Global Caribbean will become window variable.

0
source

Source: https://habr.com/ru/post/1606672/


All Articles