Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  174] [ 4]  / answers: 1 / hits: 67688  / 12 Years ago, fri, june 1, 2012, 12:00:00

How come constants cannot be set as properties of objects which are variables themselves?



const a  = 'constant' // all is well
// set constant property of variable object
const window.b = 'constant' // throws Exception
// OR
var App = {}; // want to be able to extend
const App.goldenRatio= 1.6180339887 // throws Exception


And how come constants passed by reference suddenly become variable?
EDIT: I know App won't (or rather... SHOULDN'T) be mutable; this is just an observation...



(function() {
const App;
// bunch of code
window.com_namespace = App;
}());
window.com_namespace; // App
window.com_namespace = 'something else';
window.com_namespace; // 'something else'


How can a nicely organized, extensible, object-oriented, singly namespaced library containing constants be made with these limitations?



EDIT: I believe zi42, but I just have to ask why


More From » object

 Answers
68

You cannot do it with constants. The only possible way to do something that behaves like you want, but is not using constants, is to define a non-writable property:



var obj = {};
Object.defineProperty( obj, MY_FAKE_CONSTANT, {
value: MY_FAKE_CONSTANT_VALUE,
writable: false,
enumerable: true,
configurable: true
});


Regarding your question as to why a const passed to a function becomes variable, the answer is because it's passed by value and not by reference. The function is getting a new variable that has the same value as your constant.



edit: thanks to @pst for noting that objects literals in javascript are not actually passed by reference, but using call-by-sharing:




Although this term has widespread usage in the Python community, identical semantics in other languages such as Java and Visual Basic are often described as call-by-value, where the value is implied to be a reference to the object.



[#85223] Thursday, May 31, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
coby

Total Points: 27
Total Questions: 102
Total Answers: 97

Location: Honduras
Member since Wed, Jul 14, 2021
3 Years ago
;