javascript-未捕获的语法错误:标识符 * 已被声明 [英] javascript- Uncaught SyntaxError: Identifier * has already been declared

查看:22
本文介绍了javascript-未捕获的语法错误:标识符 * 已被声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

console.log(a) //output:ƒ a(){}
var a = 1;
function a(){};
var a = 10;
console.log(a) //output:10

====================

====================

var a = 1;
if(true){
  function a(){};
  var a = 10;
}
console.log(a) // this code throws Uncaught SyntaxError: Identifier 'a' has already been declared

除了 if 块之外,上面的两个代码片段都是相同的.为什么后者在 javascript 中允许在相同的范围内使用 var 对同一变量进行两次 delcare 时会抛出错误,如下所示

both above code snippets are same except the if block.why does the latter throws error when its permissible in javascript to delcare same variable twice in the same scope with var as below

 function a(){};
 var a = 10; //no error

同样对于在上面的代码中从 `var a = 10 中删除 var 之后的稍微不同的情况,然后它工作正常但输出令人惊讶

Also for a slightly different scenario after removing var from `var a = 10 in the above code ,then it works fine but output is surprising

 var a = 1;
 if(true) {
   function a(){};
   a = 10;
 }
 console.log(a) //output:ƒ a(){}

我很惊讶地看到这个输出,因为我期待 10 ..因为在 if 块中声明的两个变量引用了上面声明的同一个变量,因为 javascript var 不尊重块范围而是功能范围......所以为什么不输出上面应该是10?当用函数表达式替换函数定义时,下面的代码输出 10 正如我预期的那样.

I am surprised to see this output as I am expecting 10 ..because two variables declared inside the if block refer to the same variable declared above as javascript var doesnt respect block scope but functional scope...so why not the output for above should be 10? where as the below code outputs 10 as i expected when replaced the function definition with function expression.

  var a = 1;
  if(true) {
    var a = function(){ console.log() }
    a = 10;
  }
  console.log(a) //output:10

推荐答案

这很令人惊讶,因为 javascript var 不尊重块作用域而是函数作用域...

This is surprising as javascript var doesn't respect block scope but functional scope...

当然,但是您没有使用 var 来声明块作用域中的 a.您使用了一个函数声明,它确实尊重块作用域(否则它将是 完全无效的代码,就像在 ES5 严格模式下一样).

Sure, but you didn't use var for the declaration of a in the block scope. You used a function declaration, which does respect block scopes (otherwise it would be completely invalid code, as in ES5 strict mode).

允许在 javascript 中使用 var 在相同的范围内声明相同的变量两次,如下所示

It's permissible in javascript to declare same variable twice in the same scope with var as below

同样适用于此.块中的 function 声明使用 ES6 声明语义(如 letconst),不允许重新声明.

Same applies here. The function declaration in the block uses ES6 declaration semantics (like let or const), which does not allow redeclarations.

这篇关于javascript-未捕获的语法错误:标识符 * 已被声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆