admin管理员组文章数量:1303335
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?
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?
Share Improve this question edited Jan 2, 2019 at 2:31 Henry Howeson asked Jan 2, 2019 at 2:16 Henry HowesonHenry Howeson 7888 silver badges21 bronze badges 12- 2 You might set a non-configurable property on the global object, but it's still a code smell. – CertainPerformance Commented Jan 2, 2019 at 2:17
-
2
const carType;
is illegal syntax. – Patrick Roberts Commented Jan 2, 2019 at 2:19 - @PatrickRoberts I know, "However you cannot define global variables without setting a value so the program will fail on the first line". I'm asking if there is any way around this – Henry Howeson Commented Jan 2, 2019 at 2:21
- 2 If you declare a variable before defining it, by definition it is not a constant, so your request makes no sense. – Patrick Roberts Commented Jan 2, 2019 at 2:25
-
2
The short answer is no - you can't create a global const, let, or class identifier in global scope using declarations within a function or by using
eval
. I looked into the eval case for this answer regarding scope. – traktor Commented Jan 2, 2019 at 2:32
1 Answer
Reset to default 10The 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);
本文标签: nodejsIs it possible to define a global constant from within a function in javascriptStack Overflow
版权声明:本文标题:node.js - Is it possible to define a global constant from within a function in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741756519a2396144.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论