如何在控制台中重新定义JavaScript(NOT CSS)类? [英] How to redefine JavaScript (NOT CSS) classes, in the console?

查看:73
本文介绍了如何在控制台中重新定义JavaScript(NOT CSS)类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JS类还很陌生,并且主要从事后端工作.

I'm fairly new to JS classes, and am doing mostly back-end work.

我正在研究新的JS类,因此我在这里开始浏览示例:

I was playing around with the new JS classes and so I started going through the examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

我转到chrome(铬)开发人员工具控制台,并编写了Polygon类:

I went to the chrome (chromium) developer tools console and I wrote the Polygon class:

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

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

Then I wanted to redefine the class, according to the example containing the methods, so I wrote:

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中有一个新的作用域,并且类会自动使用新的作用域,依此类推...但是,实际上,我该如何重新定义我的类? :D

Now I understand there's a new scoping in ES6, and that classes automatically use the new scoping and so on... but really, how do I redefine my class? :D

我通常在编写Python,因此习惯于重新定义我想要的一切.

I'm writing Python usually, so I'm used being able to redefine everything I want.

推荐答案

没有答案提供了无需更改原始代码的解决方案.因此,这里提供了完善的解决方案.

None of the answers provide a solution without changing original code... So here is refined solution.

如果在代码中您具有类似以下内容:

If in code you have something like this:

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

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

Then this means you've created a let variable named Polygon. You cannot redeclare Polygon, but you can reassign it.

因此,如果您需要进行例如JS控制台可以做到:

So if you need to experiment in e.g. JS console just do:

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

这将替换原始类,但不会违反let限制.

This will replace the original class but will not violate let restrictions.

您可以通过在控制台中粘贴以上代码来尝试此操作,然后尝试new Polygon(1,2).

You can try this out by pasting above code in the console, and then try new Polygon(1,2).

这篇关于如何在控制台中重新定义JavaScript(NOT CSS)类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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