Google Chrome片段:标识符'...'已经宣布

问题描述 投票:2回答:1

我正在使用Google Chrome的Snippets(Dev Tools内部)进行一些JS开发和测试。

在声明ES6类时,控制台会抛出一个

未捕获的SyntaxError:标识符'Foo'已在...中声明

在它第一次运行之后。

class Foo {
constructor(val) {
        this.bar = val;
    }
}

var f = new Foo('myVal');
console.log(f.bar); // prints 'myVal'

我做了一些研究,发现用{}将代码包装在块范围内有助于避免这个问题。

但是当我这样做时,虽然代码运行没有错误,但Chrome无法识别我可能对我的代码执行的任何后续编辑。

所以,如果我将上面的代码更改为以下代码:

{
    class Foo {
    constructor(val) {
            this.bar = val;
        }
    }
}

var f = new Foo('myVal');
console.log(f.bar); // prints 'myVal'

到目前为止一切正常。

现在,我意识到我的课有问题,我将代码更改为以下内容:

{
    class Foo {
    constructor(val) {
            this.bar = 'MyHardcodedVal'; // Here is the changed code
        }
    }
}

var f = new Foo('myVal');
console.log(f.bar); // STILL prints 'myVal'

如您所见,我对班级所做的编辑没有生效。

Google Chrome浏览器似乎已将我的代码放入沙盒中,该沙盒不受编辑的影响。

一种查看场景并查看Google Chrome正在执行的操作的方法是在代码中引入故意错误,然后单击Chrome在控制台中显示的错误来源。在那里,您将看到该类的代码仍然是旧的,并且根本没有更改,而在块范围之外的代码是最新的。

A few pieces of important information are highlighted: (let) The intentional mistake / ('hardcoded') The change in my class / (VM157) Top and down where you can click to see how the code looks like behind the scenes

Here you can see that behind the scene the edit to the code that was in block scope is not existent

我总是可以关闭我正在工作的标签并再次打开它,但这不切实际。

我究竟做错了什么?

是否有一种理智的方式使用Snippets进行此类测试?

希望有道理!

javascript ecmascript-6 google-chrome-devtools es6-class
1个回答
3
投票

根据评论,听起来解决方案是将整个snippet包裹在大括号中。

{
  class Foo {
    constructor(val) {
      this.bar = 'MyHardcodedVal'; // Here is the changed code
    }
  }
  var f = new Foo('myVal');
  console.log(f.bar); // STILL prints 'myVal'
}
© www.soinside.com 2019 - 2024. All rights reserved.