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 called name
  • it set on window (e.g. window.name = ...)

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -