JavaScript 变量与属性

JavaScript Variables vs Properties

在 JavaScript 中,全局变量也是 window 对象的 属性。局部变量呢?它们是任何对象的属性吗?

例如:

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
}

banana任何对象的属性

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

没有。当执行进入一个函数时,会创建一个新的declarative environment record来存储标识符。

object environment records(用于创建全局和 with 环境)不同,没有变量映射到的用户 space 对象。

另见 What really is a declarative environment record and how does it differ from an activation object?

但是您仍然可以在函数对象中存储内容。这样你就可以在像 C/C++ 这样的语言中有一个叫做 static 的变量。例如:

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

我从 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

因此,除非您为局部变量创建 getter 和 setter,否则您将无法引用它们。全局变量将变为 window 变量。