“标识符 [...] 已经被声明(...)”。如何在 Chrome Devtools 控制台中取消设置类变量?

Gre*_*een 5 google-chrome google-chrome-devtools

在 Chrome 控制台中:

# One
class A {
    constructor(x) { this.x = x }
}

class A {
    constructor(x, y) { this.x = x; this.y = y }
}

VM602:1 Uncaught SyntaxError: Identifier 'A' has already been declared(…)


# Two
class A {
    constructor(x) { this.x = x }
}
delete A
true
class A {
    constructor(x) { this.x = x }
}
VM805:1 Uncaught SyntaxError: Identifier 'A' has already been declared(…)


# Three
A = null
null
class A {
    constructor(x) { this.x = x }
}
VM817:1 Uncaught SyntaxError: Identifier 'A' has already been declared(…)
Run Code Online (Sandbox Code Playgroud)

而且根本没有机会在没有页面重新加载的情况下取消设置变量。有没有办法在不重新加载页面的情况下删除/清除/取消设置它?

Ale*_*nko 3

我也在找这个问题。但在网上找不到一些有用的东西。

因此使用了下一个解决方法:声明与类同名的变量。像这样:

var A = class A { constructor(x) { this.x = x } }

new A(2)
> A {x: 2}
Run Code Online (Sandbox Code Playgroud)

这样就很容易重新定义:

var A = class A { constructor(x, y) { this.x = x; this.y = y } }
new A(2,3)
> A {x: 2, y: 3}
Run Code Online (Sandbox Code Playgroud)

即使我们使用另一个变量,我们仍然得到类型为“A”的对象

var AZ = class A {  constructor(x, y) { this.x = x; this.y = y } }
new AZ(2,3)
> A {x: 2, y: 3}
Run Code Online (Sandbox Code Playgroud)

但是我们不能通过类名来使用类,只能通过变量来使用:

var C = class B {    constructor(x, y) { this.x = x; this.y = y } }
new C(2,3)
> B {x: 2, y: 3}
new B(2,3)
> VM342:1 Uncaught ReferenceError: B is not defined
Run Code Online (Sandbox Code Playgroud)