Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / ES6

JavaScript ES6 Private Fields and Methods

4.86/5 (7 votes)
26 Nov 2017CPOL 7.7K  
How to create private fields and methods within JavaScript ES6 classes.

Introduction

Below is an example I created, demonstrating how to create private fields and methods within JavaScript ES6 classes.

Example Code

I was able to achieve private fields and methods by doubling class with class.

JavaScript
// Private Class Definition
class test
{
    // Private Method
    get(){ console.log('Private Get Hello'); }

    // Private class constructor
    constructor()
	{
        // Private Fields
        this.fields = [];

        // Private Instance
        const self = this;

        // Public Class Definition
        class test
        {
            // Public Properties to Private Fields
	        set counter(_counter) { self.fields['counter'] = _counter; }
            get counter() { return self.fields['counter']; }

            // Public Constructor
            constructor()
            {
                console.log(arguments);
            }

            // Public Method
            increase()
            {
                self.fields['counter'] += 1;
                console.log(self.fields);
            }

            // Public Method to Private method
            get()
            {
                self.get();
            }
        }

        return new test(...arguments);
    }
}

var a = new test(54321,'abc');
console.log(a);
a.counter = 1234;
a.increase();
a.get();
console.log(a.fields);  // <-- Undefined Private

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)