简体   繁体   English

在函数中声明变量的不同方法-它们有何不同?

[英]Different ways of declaring variables within functions -how do they differ?

I have seen two different ways to declare variables within functions. 我已经看到了两种在函数内声明变量的不同方法。 How do they differ? 它们有何不同? Thank you. 谢谢。

Namespace.Class = function() {
    // first way. use "var".
    var variable1 = 'value';

    // second way. use "namespace".
    Namespace.Class.variable2 = 'value';
};

var declares a local variable, meaning it's only visible from within the function, while the second way is for declaring a member of the object, which will be visible from everywhere. var声明一个局部变量,这意味着它仅在函数内部可见,而第二种方法是声明该对象的成员,该成员将在任何地方都可见。

A tutorial on Javascript variables: http://www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3 有关Javascript变量的教程: http : //www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3

Edit: A tutorial on private members in JS: http://www.crockford.com/javascript/private.html 编辑: JS中的私人成员教程: http : //www.crockford.com/javascript/private.html

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

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