0

Does this code make my Number "save"?

Hey, it's difficult to write in the title what I want. So sorry, if the title doesn't make much sense ;) I wanted to create a variable or container that contains a number as a value. The value has to be a number and I want to get notified if it got changed. I came up with the following idea: const saveNumber = (function () { var numberValue = null; return { set value(value){ console.warn('Number was changed!'); if(typeof value !== 'number') { throw 'Value has to be a number!'; return; } numberValue = value; }, get value(){ return numberValue; } } })(); This leads to the following behaviour: saveNumber.value = 5; // "Number was changed!" saveNumber.value = "Strings don't work"; // throws 'Value has to be a number!' console.log(saveNumber.value); // 5 So in my opinion I created some kind of a "save" number or value. I call it saved since the value can't be manipulated directly or in other words without using the setter function. In addition it's save because I get notified as soon as the value gets changed. My question is: Does this code make sense and does it really lead to the above described behaviour? Or is the still a way to change the numberValue without using the getter function? Thank you!

23rd Oct 2018, 12:00 PM
Mitch
Mitch - avatar
2 odpowiedzi
0
In your code example the value is in the closure of the returned object and inaccessible from the outside. Take a look at Object.defineProperty() (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) Ist's a way to define a property directly with getter and setter. and be aware that NaN is also of type number.
25th Oct 2018, 6:59 PM
Andreas
Andreas - avatar
0
Hey, thanks for your answer! You said: "In your code example the value is in the closure of the returned object and inaccessible from the outside." That's the whole point of my code :) I think I didn't explain very well what I wanted to achieve... I'll have a look at Object.defineProperty() since I don't know it yet. Thanks again!
28th Oct 2018, 2:39 PM
Mitch
Mitch - avatar