如何在控制台中重新定义 JavaScript(不是 CSS)类?

How to redefine JavaScript (NOT CSS) classes, in the console?

我对 JS classes 还很陌生,主要从事后端工作。

我在玩新的 JS classes,所以我开始浏览这里的示例:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

我去了 chrome (chromium) 开发者工具控制台并编写了 Polygon class:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

然后我想根据包含方法的例子重新定义class,所以我写了:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
}

这引发了一个错误:Uncaught SyntaxError: Identifier 'Polygon' has already been declared(…)

现在我明白了 ES6 中有一个新的作用域,classes 会自动使用新的作用域等等......但实际上,我该如何重新定义我的 class? :D

我平时都是在写Python,所以我习惯了可以重新定义我想要的一切。

我使用的是 Chrome 的版本 54.0.2840.71(64 位),虽然我可以打开控制台并声明一个新的 class,但我无法重新定义 class(你会得到错误:VM272:1 Uncaught SyntaxError: Identifier 'Thing' has already been declared,因为我试图重新定义我的 class Thing)。

如果您只是想稍后将方法添加到 class,您可以将它们添加到 class 的 prototype:

Polygon.prototype.area = function() {
  // do some stuff
}

但是,在这种情况下,它不会像您的示例中那样是 getter 方法。

编辑

要解决语法错误,如果您只是将 class 重新分配为变量,它应该会执行您想要的操作:

// in your original code

var Polygon = class{}

// in the console

var Polygon = class {
  // with new stuff
}

块作用域声明(letconstclass)无法重新声明。

Class expressionvar 可用于在控制台中重新使用和重新声明变量:

var Polygon = class Polygon  { ... };
new Polygon();
var Polygon = class Polygon  { ... };
new Polygon();

None 的答案提供了不更改原始代码的解决方案...所以这里是改进的解决方案。

如果在代码中你有这样的东西:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

那么这意味着您已经创建了一个名为 Polygonlet 变量。您不能重新声明 Polygon,但可以重新分配它。

因此,如果您需要进行实验,例如JS 控制台只是做:

Polygon = class {
  //... new stuff here
}

这将取代原来的 class 但不会违反 let 限制。

您可以通过将上面的代码粘贴到控制台来进行尝试,然后尝试 new Polygon(1,2)