How to check that ES6 “variable” is constant?

前端 未结 4 1493
一整个雨季
一整个雨季 2020-12-11 17:18

Does anyone know some tricks how to do it? I tried to use try-catch:

\"use strict\";

const a = 20;

var isConst = false;
try {
   var temp = a;         


        
4条回答
  •  天命终不由人
    2020-12-11 18:22

    Based on some of the answers here I wrote this code snippet (for client side JS) that will tell you how a "variable" was last declared--I hope it's useful.

    Use the following to find out what x was last declared as (uncomment the declarations of x to test it):

    // x = 0
    // var x = 0
    // let x = 0
    // const x = 0
    
    const varName = "x"    
    console.log(`Declaration of ${varName} was...`)
    try {
      eval(`${varName}`)
      try {
        eval(`var ${varName}`);
        console.log("... last made with var")
      } catch (error) {
        try {
          eval(`${varName} = 0`)
          console.log("... last made with let")
        } catch (error) {
          console.log("... last made with const")
        }
      }
    } catch (error) {
      console.log("... not found. Undeclared.")
    }

    Interestingly, declaring without var, let or const, i.e x = 0, results in var getting used by default. Also, function arguments are re-declared in the function scope using var.

提交回复
热议问题