+ 1
Private methods in javascript.
How do I create private methods in javascript classes?
6 ответов
+ 2
with an IIFE (immediatly invoked function execution):
var MyClass = (function() {
function private() {
alert('only code in this IIFE can access this private function');
alert('from private, this = '+JSON.stringify(this,null,' '));
}
return class MyClass {
constructor(props) {
Object.assign(this,props);
}
public() {
alert('public method');
private.call(this);
}
};
})();
that define a private function accessible only from code inside the IIFE where it is defined...
to use it as an object method, call it by binding 'this' to it (see Function methods bind, call, and/or apply)
https://medium.com/@jhawleypeters/javascript-call-vs-apply-vs-bind-61447bc5e989
https://www.codementor.io/@niladrisekhardutta/how-to-call-apply-and-bind-in-javascript-8i1jca6jp
+ 1
Simple google search lead me to https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes
I hop it helps
+ 1
You could use closure to set private fields and methods. Here an example
var calnums = function() {
// private method
var getprivatenum = function () {
// secret business logic here to get 100 ...
return 100;
}
// privte field
var num = getprivatenum(); // init num
return {
// public method
add: function(n) { // add input with private num
num += n;
},
// public method
sum: function() { // return private num
return num;
}
}
}
try {
var inputnums = calnums();
inputnums.add(2); // add with privatenum
inputnums.add(3);
inputnums.add(6);
inputnums.add(4);
inputnums.add(5);
var sum = inputnums.sum();
console.log(sum); // get 120
var inputnums1 = calnums();
inputnums1.getprivatenum();
} catch (err) {
// error: can't access private method
console.log(err.message);
}
https://code.sololearn.com/chN993zel4NN/?ref=app
+ 1
I only noticed that OP mentions private method in class now.
Class properties are public by default and can be examined or modified outside the class. There is however a stage 3 proposal to allow defining private class fields using a hash # prefix.
More information
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields
I tried to convert my previous example to class here, please check it out.
class CallNum {
// privte field
#num = 0; // init num
constructor() {
// console.log("init");
this.#num = this.#getPrivateNum()
}
// private method
#getPrivateNum() {
// secret business logic here to get 100 ...
return 100;
}
// public method
add(n) { // add input with private num
this.#num += n;
}
// public method
sum() { // return private num
return this.#num;
}
}
full code: (webview and 74)
https://code.sololearn.com/We9U8jxXR40H/?ref=app
0
Mirielle[ Exams ]
you're right about strictly private methods: they are still mostly not supported...
however, under the hood, private methods (when supported) are only a way of binding a function with 'this', by hidding the bind/call/apply stuff ^^