I would like to be able to define a constant that is in the global scope from within a function. With a normal variable this would be possible by defining it outside the function and setting its' value from within the function as shown below:
var carType;
function carType(){
carType = 'Reliant Robin';
}
However you cannot define global variables without setting a value so this would not work with a constant, is there any way around this?
The answer is "yes", but it is not a typical declaration, see the code snippet below
function carType(){ Object.defineProperty(window, 'carType', { value: 'Reliant Robin', configurable: false, writable: false }); } carType(); carType = 'This is ignored' console.log(carType);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.