user386167
user386167

Reputation:

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';
};

Upvotes: 1

Views: 574

Answers (1)

escargot agile
escargot agile

Reputation: 22389

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

Upvotes: 6

Related Questions