What is the drawback of creating true private methods in JavaScript ?
According to other programming languages like c++, java, etc. private is something that can’t be shared with other classes, which cannot be accessed directly using objects. The same rule applies to JavaScript also.
So first we have to look at how private methods are made using JavaScript? There are mainly four keywords using that we can make a private method in the class.
- var
- let
- const
- # (hash)
Example:
Javascript
<script>
var Geek = function (article, published) {
this .programmingLang = "Js" ;
var topic = "private_method" ;
var status = published;
var publish = () => {
console.log(article);
return status;
}
console.log(publish());
};
var Geek1 = new Geek( 'ABC' , 'YES' );
console.log(Geek1.programmingLang);
<script/>
|
Output:
ABC
YES
Js
There are two major disadvantages of creating the true private method in JavaScript.
- Cannot call private method outside the class.
- Create memory inefficiency when different objects are created for the same class, as a new copy of the method would be created for each instance.
Example: If we call a private member function outside the class, then in that case it gives an error.
Javascript
<script>
var Geek = function (article, published) {
this .programmingLang = "Js" ;
var topic = "private_method" ;
var status = published;
var publish = () => {
console.log(article);
return status;
}
console.log(topic);
};
var Geek1 = new Geek( 'ABC' , 'YES' );
console.log(Geek1.programmingLang);
console.log(publish());
<script />
|
Output:
But below example gives the correct output:
Javascript
<script>
class A {
#foo;
constructor(foo) {
this . #foo = "ABC";
}
#privateFun(prefix) {
return prefix + this . #foo;
}
publicFun() {
return this . #privateFun(">>");
}
}
let a = new A();
console.log(a.publicFun());
<script/>
|
Output:
>>ABC
Example: If we create a different object for the same class, then in that case each object creates its own instance or say a copy of the function for itself. Then in that case memory inefficiency problem arises
Javascript
<script>
var Employee = function (name, comp, sal) {
this .name = name;
this .company = comp;
this .salary = sal;
var Sal_increase = () => {
this .salary = this .salary + 45000;
};
this .dispalySal = () => {
Sal_increase();
console.log( this .salary);
};
};
const A = new Employee( "A" , "dream" , 45000);
const B = new Employee( "B" , "young" , 6000);
const C = new Employee( "C" , "inspire" , 9000);
A.dispalySal()
B.dispalySal()
C.dispalySal()
</script>
|
Output:
90000
51000
54000
Note: The code here mentioned can be run using inside HTML or a console.
Last Updated :
21 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...