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;
}
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:
var
(name = ...
, and there is no other visible local variable called name
window
(e.g. window.name = ...
)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
})();
})();