Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

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

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

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

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;
  }
}

This raises an error: Uncaught SyntaxError: Identifier 'Polygon' has already been declared(…)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
  }
}

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

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...