javascript class methods - javascript class properties - Javascript classes

Javascript Classes: A Long-Awaited Feature in Javascript ES6

When first created in the 1990s, Javascript was specialized for the capabilities of the web at that time. Large Javascript codebases and reusable classes were almost inconceivable in the early days of the Internet, when browsers like Netscape Navigator (which few people today have even heard of) were popular.

The modern Javascript standard showcases Javascript’s evolution into a full-featured programming language. Javascript ES2015, also known as Javascript ES6, gave developers the ability to build complex classes and keep up with the demands of the modern web.

This article describes how to create Javascript classes. It also explains the current level of support for Javascript classes across various browsers and what this means for cross-browser compatibility.

Javascript Classes Overview

Javascript classes are an implementation of object-oriented programming principles which give reusable code states and behaviors. Javascript classes can store data and perform actions. Developers used Javascript objects to emulate classes for years, but those did not have the same functionality as true classes, as the next section describes.

The syntax of Javascript classes is significantly different from simple objects. A class starts with the reserved keyword class and contains constructors, class properties (also known as fields), and class methods.

class MyExample {                      // Class declaration
    myPublic;                          // Public property
    #myPrivate;                        // Private property
    static myStatic;                   // Static property

    constructor(param1, param2) {      // Constructor
        this.myPublic = param1;
        this.#myPrivate = param2;
    }

    seePublic() { return this.myPublic; }      // Public method
    #seePrivate() { return this.#myPrivate; }  // Private method
    static seeStatic() { return myStatic; }    // Static method
};

Public Class Properties

Public class properties are accessible directly from an instance of a class. Define them by name inside a class. They don’t need to be defined immediately inside a constructor, but it’s good practice to do so for code clarity.

let example1 = new MyExample(1, 2);
console.log(example1.myPublic);  // 1

Private Class Properties

Private class properties are accessible only inside the class. Define them by prefixing a hash mark (#) and initializing them inside the class constructor. A browser will throw an error if you do not define a private class property in a constructor or if you try to access the private class property directly.

let example2 = new MyExample(1, 2);
console.log(example2.myPrivate);  // Error!

Static Class Properties

Static class properties are accessible inside any instance of a class. There may be only one instance of this property among all classes (so, one myStatic for all instances of MyExample) and the property may not include the const keyword.

// in a class
const static example3a = "test";  // Error!

// Access the static property in the "MyExample" class
console.log(MyExample.myStatic);

// Set the static property for all instances of the "MyExample" class
MyExample.myStatic = "abc";

Class Constructors

Javascript class constructors initialize an instance of a class. They may have parameters that set public or private class methods, but are not required to.

The constructor() function name is always required. Class constructors initialize the class execution context, denoted by the this keyword.

This example shows a constructor with one argument that initializes a public class field in the class’s execution context.

class Example4a {
    param;

    constructor(arg) {
        this.param = arg;
    }
}

Public Class Methods

Public class methods, like public class properties, are accessible directly from an instance of a class. Define them by name inside a class with any associated parameters. Since they are part of a class, they don’t require the function keyword.

This example expands on the previous example to add a public class method without parameters and a public class method with a parameter to the Example4a class.

class Example4a {
    param;

    constructor(arg) {
        this.param = arg;
    }

    publicNoParams() { return this.param; }
    publicParams(arg1) { return arg1; }
}

Private Class Methods

Private class methods are defined just like public class properties, with one small but important change. Define them by prefixing an hash mark (#). Like a private class, you cannot access a private method directly from a class instance.

This example expands on the previous example to add a private class method without parameters and a private class method with a parameter to the Example4a class. It also shows how calling a private method on a class instance causes an error.

class Example4a {
    param;
    #param2;

    constructor(arg, arg2) {
        this.param = arg;
        #this.param2 = arg2;
    }

    publicNoParams() { return this.param; }
    publicParams(arg1) { return arg1; }

    #privateNoParams() { return this.param; }
    #privateParams(arg2) { return arg2; }
}

let example5 = new Example4a(1, 2);
console.log(example5.publicNoParams());    // OK
console.log(example5.#privateNoParams());  // Error!

Static Class Methods

Static class methods, like static class properties, are accessible inside any instance of a class. There may be only one instance of this method among all classes.

Static class methods may be either public or private. Only access other static variables inside static methods; if you access instance variables Javascript will throw an error.

This example expands on the previous example to add a public static class method without parameters and a private static class method with a parameter to the Example4a class. It also shows how using non-static class variables in a static method or calling a static method in a non-static way causes an error.

class Example4a {
    param;
    #param2;
    static param3 = 100;

    constructor(arg, arg2) {
        this.param = arg;
        #this.param2 = arg2;
    }

    publicNoParams() { return this.param; }
    publicParams(arg1) { return arg1; }

    #privateNoParams() { return this.param; }
    #privateParams(arg2) { return arg2; }

    static getParam3() { return Example4a.param3; }
    static #setParam3(arg3) { Example4a.param3 = #param2 + arg3; }  // Error because #param2 is not static
}

How Much Support Exists in Browsers?

As of this writing, most modern browsers fully support Javascript classes. There are some significant exceptions, and developers should be aware of them to keep class data secure.

Internet Explorer has no support for Javascript classes, and it won’t ever support them, since it will be retired in 2022. Its successor, Microsoft Edge, has full support for Javascript classes, including constructors, public methods, and private methods.

Firefox and Firefox for Android do not support private class properties. On those browsers all Javascript class properties are public and Javascript does not yet supply full encapsulation of private data. Be sure to take this into account when designing data and code for Firefox compatibility.

Samsung Internet, a popular browser on some Android smartphones, does not support class properties of any kind. The Samsung browser’s documentation claims to fully support classes, but browser testing currently contradicts the documentation on class properties. This could be a source of significant confusion and headaches.

Support for Javascript classes across modern browsers has risen quickly since the release of ES2015, and there is reason to believe that two of these browsers will have more support soon. Firefox and Firefox for Android are currently testing private class fields as an experimental feature. Developers can manually enable private class fields to test them, but support for fields is not enabled by default (or widespread).

Since support for Javascript classes is relatively solid, but still has some cross-browser kinks, test for class support and create fallbacks where necessary. The only way to reliably handle class variables across all browsers is to pass values into and out of class methods. Constructors, public methods, and private methods are reliable across modern browsers.

Conclusion

Javascript classes represent a major step forward in Javascript object-oriented programming. They do not replace simpler Javascript objects completely, however; you should not assume that every Javascript object would be better implemented as a class.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript classes and other programming concepts.

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni