How do you check the difference between an ECMAScript 6 class and function?

I think the simplest way to check if the function is ES6 class is to check the result of .toString() method. According to the es2015 spec: The string representation must have the syntax of a FunctionDeclaration FunctionExpression, GeneratorDeclaration, GeneratorExpression, ClassDeclaration, ClassExpression, ArrowFunction, MethodDefinition, or GeneratorMethod depending upon the actual characteristics of the object So the … Read more

How do I use a static variable in ES6 class?

Your class has no static variables (if by static variable you mean static property). getCount returns NaN (after you call increaseCount) because Animal has no count property initially. Then increaseCount does undefined + 1 which is NaN. Instances created by new Animal have a count property initially, but Animal itself does not until you call … Read more

Serializing an ES6 class object as JSON

As with any other object you want to stringify in JS, you can use JSON.stringify: JSON.stringify(yourObject); class MyClass { constructor() { this.foo = 3 } } var myClass = new MyClass() console.log(JSON.stringify(myClass)); Also worth noting is that you can customize how stringify serializes your object by giving it a toJSON method. The value used to … Read more

How and why would I write a class that extends null?

EDIT (2021): TC39, which specifies JavaScript still hasn’t resolved exactly how this is supposed to work. That needs to happen before browsers can consistently implement it. You can follow the latest efforts here. Original answer: Instantiating such classes is meant to work; Chrome and Firefox just have bugs. Here’s Chrome’s, here’s Firefox’s. It works fine … Read more