繁体   English   中英

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是任何物体的财产

局部变量怎么样? 它们是任何物体的属性吗?

当执行进入函数时,会创建一个新的声明性环境记录来存储标识符。

不同于对象环境记录 (用于创建全局和with环境)有哪个变量被映射没有用户空间物体。

另请参见什么是声明性环境记录,它与激活对象有何不同?

但是你仍然可以在函数对象中存储东西。 通过这种方式,您可以在C / 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

我从范围中提取并修改,以便您可以学习更多技巧。 检查这个例子。

<!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,否则您将无法引用它们。 全球漫画将变成窗口可变形。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM