JavaScript Classes

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • class Foo {}
  • class Foo extends Bar {}
  • class Foo { constructor() {} }
  • class Foo { myMethod() {} }
  • class Foo { get myProperty() {} }
  • class Foo { set myProperty(newValue) {} }
  • class Foo { static myStaticMethod() {} }
  • class Foo { static get myStaticProperty() {} }
  • const Foo = class Foo {};
  • const Foo = class {};

Remarks

class support was only added to JavaScript as part of the 2015 standard.

Javascript classes are syntactical sugar over JavaScript's already existing prototype-based inheritance. This new syntax does not introduce a new object-oriented inheritance model to JavaScript, just a simpler way to deal with objects and inheritance. A class declaration is essentially a shorthand for manually defining a constructor function and adding properties to the prototype of the constructor. An important difference is that functions can be called directly (without the new keyword), whereas a class called directly will throw an exception.

class someClass {
    constructor () {}
    someMethod () {}
}
 
console.log(typeof someClass);               
console.log(someClass);
console.log(someClass === someClass.prototype.constructor);                         
console.log(someClass.prototype.someMethod);
 
// Output:
// function
// function someClass() { "use strict"; }
// true
// function () { "use strict"; }

If you are using an earlier version of JavaScript you will need a transpiler like or in order to compile the code into a version that the target platform will be able to understand.



Got any JavaScript Question?