Declaring variables without a value

旧时模样 提交于 2019-12-20 23:33:28

问题


I wish to create a Javascript object with nested variables where some of the variables will not have a default value specified.

I currently have this:

var globalVarA = "foo";
var globalVarB = "bar";
var globalVarC;

function myFunction(){
  //do something
}

I wish to change this to:

var myObject = {
  GlobalVars: {
     globalVarA: "foo",
     globalVarB: "bar",
     globalVarC
  },
  myFunction: function(){
     //do something
  }
}

However I get the following error:

Expected ':'

How can I declare this variable without a value?

Is this the best practice or is there an alternative better solution?


回答1:


If you want to define the variables as properties of GlobalVars you have to explicitly assign undefined to them

GlobalVars: {
     globalVarA: "foo",
     globalVarB: "bar",
     globalVarC: undefined
  },

Your code contained invalid notation, when using object literal notation you must specify a value for each variable. This is unlike other notations like XML or formParams where you can declare a attribute/property without setting it.

Note, that in my solution undefined variables do get a default value - that value is just the primitive value undefined which is what is returned by default for variables that were not defined.

However, your variable does get defined if you do globalVarC: undefined

GlobalVars.globalVarC;//undefined
GlobalVars.globalVarX;//undefined
GlobalVars.hasOwnProperty("globalVarC");//true
GlobalVars.hasOwnProperty("globalVarX");//false

From the spec:

4.3.9 undefined value:

primitive value used when a variable has not been assigned a value.




回答2:


You need to specify a value for globalVarC else the javascript syntax for json will be wrong, since you do not have any value to initialize you can give the value undefined.

undefined is a global variable with primitive value undefined.

var myObject = {
  GlobalVars: {
     globalVarA: "foo",
     globalVarB: "bar",
     globalVarC: undefined
  },
  myFunction: function(){
     //do something
  }
}



回答3:


You will want the undefined primitive value to be the default value:

var myObject = {
  GlobalVars: {
     globalVarA: "foo",
     globalVarB: "bar",
     globalVarC: void 0
  },
  myFunction: function(){
     //do something
  }
}

The void 0 expression gives the value of undefined, regardless of whether undefined was "rerouted".



来源:https://stackoverflow.com/questions/15523638/declaring-variables-without-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!