Unlock the Secrets: Mastering Private and Public Methods in Pure JavaScript

0 0
Read Time:20 Second

Have you been creating your own classes in pure JavaScript?

What if you neeed a private method? How to create them?

var MyClass = (function() {
        function MyClass() {
        }

        var prvMethod = function() {
               console.log('method');
        };

        MyClass.prototype = {
            init: function() {
                console.log('init ');
                prvMethod();

            }

        };

        return MyClass;
    })();

var mc = new MyClass();
mc.init();

So finally you can access init() but cannot access prvMethod(). It has only access into MyClass() function scope.

About Post Author

Piotr Sikora

Piotr Sikora Founder of WolePapierowe.com Co-founder of Liderazgo.pl MeetJS Kielce Committee member. JavaScript and Python enthusiast.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *

© UiCore 2024. All Rights Reserved.