简体   繁体   中英

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.

A tutorial on Javascript variables: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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