Click here to Skip to main content
15,889,909 members
Articles / Programming Languages / ECMAScript 6
Tip/Trick

JavaScript ES6 Private Fields and Methods

Rate me:
Please Sign up or sign in to vote.
4.86/5 (7 votes)
26 Nov 2017CPOL 7.5K   4   1
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)


Written By
Software Developer (Senior) Codevendor
United States United States
Please visit my personal website https://codevendor.com for my latest codes and updates.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Jay Bardeleben30-Dec-17 10:20
professionalJay Bardeleben30-Dec-17 10:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.