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
 |  Show 7 more ments

1 Answer 1

Reset to default 10

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);

本文标签: nodejsIs it possible to define a global constant from within a function in javascriptStack Overflow