0

I have a JavaScript function which has a static variable:

function Constants() {

}

Constants.i = '1';

Now according to ECMA 6 we have const keyword. Using this we can make a variable as immutable.

I am not able to find how to use const keyword with function static variable, if I use like below it is not loading the function:

const Constant.i = '1';

It will be very helpful if anyone can suggest the proper way of doing the same.

3
  • There are no static variables in JavaScript. What you have is a property. There are ways to make it non-writable, but not using a keyword or declaration like const. Commented Mar 2, 2016 at 11:54
  • const Constant.i = '1'; it will raise an error. Probably it will help you Object.defineProperty Commented Mar 2, 2016 at 11:55
  • const is not making a variable immutable, it just makes sure the reference to the value won't change. Commented Mar 2, 2016 at 12:01

1 Answer 1

1

const only works for variables, not for object (or function) properties.

As mentioned above, you can use Object.defineProperty to define an object property that cannot be changed:

function Constants() {

}

Object.defineProperty(Constants, 'i', {
    value: '1',
    writable: false, // this prevents the property from being changed
    enumerable: true, // this way, it shows up if you loop through the properties of Constants
    configurable: false // this prevents the property from being deleted
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.