How to use constant in javascript?

Using Javascript from SpiderBasic
sworteu
Posts: 18
Joined: Sun Feb 07, 2016 9:49 am

How to use constant in javascript?

Post by sworteu »

I know how to use variables, pointers and functions but how to add constants to javascript?
Fred
Site Admin
Posts: 1506
Joined: Mon Feb 24, 2014 10:51 am

Re: How to use constant in javascript?

Post by Fred »

You mean PureBasic constants ? If yes, it's not possible, as it's resolved by the compiler before generating the JS.
sworteu
Posts: 18
Joined: Sun Feb 07, 2016 9:49 am

Re: How to use constant in javascript?

Post by sworteu »

Fred wrote:You mean PureBasic constants ? If yes, it's not possible, as it's resolved by the compiler before generating the JS.
I see, that's a pitty.

This is the right way then?

Code: Select all

Procedure Some()
const.s = #myconstant
!document.title= v_const
EndProcedure
Fred
Site Admin
Posts: 1506
Joined: Mon Feb 24, 2014 10:51 am

Re: How to use constant in javascript?

Post by Fred »

Looks OK.
dunufoku
Posts: 1
Joined: Wed Aug 15, 2018 12:51 pm

Re: How to use constant in javascript?

Post by dunufoku »

Try this

Code: Select all

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1
Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.

If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.

punjabi status
Post Reply