简体   繁体   中英

JS - set a global variable

I want to set a global variable via a set function but it always sets it to undefined value:

var name;
var setName = function(name){
    this.name = name;
}

In this case you don't use this . (It could work but not necessarily. Why? Read this )

Just use:

var name;
var setName = function (aname) {
    name = aname;
}

Also make sure this code is not inside of another scope (function):

function foo() {
    // ...
    var name;
    var setName = function (aname) {
        name = aname;
    }
    // ...
}

In this case name would not be global and you would have to omit its declaration to make it global:

function foo() {
    // ...
    var setName = function (aname) {
        name = aname; // not it is global, if not defined in the visible scope
    }
    // ...
}

But this is a bad practice, so try to avoid polluting the global namespace . A variable is considered in the global namespace if:

  • it has no var ( name = ... , and there is no other visible local variable called name
  • it is set on window (eg window.name = ... )
function(val){

    name = val

.......................

First, window.name is a reserved property, and you should not use it.

Second, it's a good idea to namespace any global JavaScript, to avoid those types of issues or conflicts with third party libraries.

Here's a working example:

window.MyNamespace = {};
MyNamespace.name = '';
MyNamespace.setName = function(value) {
    MyNamespace.name = value;
};
MyNamespace.setName('hello');
MyNamespace.name; // "hello"

Based on your comment about this being in a module, this code will work:

(function(){ 
    app = {};  
    app.myPerson = (function(){ 
        var name;
        var setName = function(value) {
            name = value;
        };      
        setName('Charlie');
        console.log(name); // Charlie
    })();        
})(); 

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