2

I have a server-side javascript file that translates an XML request to a JSON response (and vice-versa) and performs some business logic.

The XML element names come from a schema that is part of a different project.

To prevent minor typo's from causing major bugs, and to make dealing with schema changes relatively painless, I would like to extract the element names to variables.

In Java, I would either use variables of the type static final String or an enum to do this.

public class Names {
    public final static String CUSTOMER_ZIPCODE = "POstal_code";
    public final static String CUSTOMER_LASTNAME = "last-name";
    public final static String EMPLOYEE_LASTNAME = "lastName";
}

Now when element names change in the schema, I just update the Names class. (Notice also the real-world inconsistent spelling of elements.)

The variables can then be used:

createElement(Names.CUSTOMER_LASTNAME, "Spolsky");

Resulting in:

<bla:last-name>Spolsky</bla:last-name>

Is there any way to do this is javascript?

Ivana
  • 643
  • 10
  • 27
  • Since ES2015 javascript has a "const" keyword. Link https://stackoverflow.com/questions/130396/are-there-constants-in-javascript – tomas Aug 03 '17 at 11:08

2 Answers2

3

I believe what you are looking for is const.

Constants You can create a read-only, named constant with the const keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign ($) and can contain alphabetic, numeric, or underscore characters.

for example, you can say const CUSTOMER_ZIPCODE = "POstal_code";

QuakeCore
  • 1,886
  • 2
  • 15
  • 33
0

You can try something like this:

 function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = getAppleInfo;
}



function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
}

To instantiate an object using the Apple constructor function, set some properties and call methods you can do the following:

var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

For further information please refer to this link

In order to use constant in javascript please refer the question here

Chetan chadha
  • 558
  • 1
  • 4
  • 19
  • I don't understand this answer, unless you mean to say that the String values should be modeled as functions. I considered this, actually it was plan B, but it made de code less clear. – Ivana Aug 04 '17 at 07:38