0

Why wrap a class in a var?

What does example B give you that example A doesn't? EXAMPLE A class Rectangle { constructor(height, width) { this.height = height; this.width = width; } } EXAMPLE B var Rectangle = class { constructor(height, width) { this.height = height; this.width = width; } }

24th Apr 2020, 11:02 PM
John Weiss
John Weiss - avatar
1 Resposta
0
Considering only your code samples, there's no benifits to use B (class expression) against A (class declaration)... but that's only the simplest use case of class expressions: the real benefits would come with the fact that a class expression could be used anywhere an expression could be used, as the name suggest ;) You could say that's almost a taste question, but a few more realistic case would be one where the class expression give advantage over equivalent done with class declaration: // expressions assigned to object properties (namespace): const shapes = { Rect: class { constructor(x,y,w,h) {} }, Disc: class { constructor(x,y,r) {} }, }; // declaration force to declare classes outside, and assign them to object properties after (much verbose, less readable, and potentially pollute global scope unless you wrap all stuff in an IIFE): class Rect { constructor(x,y,w,h) {} } Disc: class { constructor(x,y,r) {} } const shapes = { Rect: Rect, Disc: Disc, };
26th Apr 2020, 12:05 AM
visph
visph - avatar