简体   繁体   中英

JavaScript constants and object literals

I know I can do this in JavaScript:

RequestDate: {
    '0' : 'previous_activity_date',
    '1': 'next_activity_date'
  }

And I can do this:

this.RequestDate = {};
this.RequestDate[App.FORWARD] = 'next_activity_date';
this.RequestDate[App.BACK] = 'previous_activity_date';

Is there a way of making the following work:

RequestDate: {
    App.Back : 'previous_activity_date',
    App.Forward: 'next_activity_date'
  },

The above obviously errors, is there a way to make it work?

you can do this.

RequestDate: {
    [App.Back]: 'previous_activity_date',
    [App.Forward]: 'next_activity_date'
  }

Short answer: no. You can only have literal keys in the object literal. Your own solution is the best one if you want to use constants.

http://bclary.com/2004/11/07/

11.1.5 Object Initialiser

An object initialiser is an expression describing the initialisation of an Object, written in a form resembling a literal. It is a list of zero or more pairs of property names and associated values, enclosed in curly braces. The values need not be literals; they are evaluated each time the object initialiser is evaluated.

As you have noticed, you can write this:

RequestDate = {};
RequestDate[App.Back] = 'previous_activity_date';
RequestDate[App.Forward] = 'next_activity_date';

But the javascript syntax does not allow an expression before the : of the JSON notation.

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