javascript - JS - set a global variable -
i want set global variable via set function sets undefined value:
var name; var setname = function(name){ this.name = name; }
in case don't use this. (it work not necessarily. why? read this)
just use:
var name; var setname = function (aname) { name = aname; } also make sure code not inside of scope (function):
function foo() { // ... var name; var setname = function (aname) { name = aname; } // ... } in case name not global , have omit declaration make global:
function foo() { // ... var setname = function (aname) { name = aname; // not global, if not defined in visible scope } // ... } but bad practice, try avoid polluting global namespace. variable considered in global namespace if:
- it has no
var(name = ..., , there no other visible local variable calledname - it set on
window(e.g.window.name = ...)
Comments
Post a Comment