Is this the correct way to do private functions in Javascript / node.js?
Update from May 17, 2019
In ESNext, which is the next specification of javascript, the support of private methods and attributes has been added.
To make an attribute or a function private, use the character #
.
class Foo {
#privateAttribute = 'hey';
showPrivate() {
console.log(this.#privateAttribute);
}
}
It has been implemented in node.js v12+.
You can configure babel to transpile it using the following plugin.
It requires babel v7.0.0+.
Simplest way to have a private function is to just declare a function outside of the class. The prototype functions can still reference it perfectly fine, and pass their this
scope with .call()
function privateFunction() {
console.log(this.variable)
}
var MyClass = function () {
this.variable = 1;
}
MyClass.prototype.publicMethod = function() {
privateFunction.call(this);
}
var x = new MyClass();
x.publicMethod()
Whatever you will not add to module.exports
will be private for that module
and can not be accessed from outside of the module.
Also inside the controller store the reference of this
into a local variable
var self = this;
You can use revealing module pattern.
var myNameSpace = function() {
var current = null;
function init() {
…
}
function change() {
…
}
function verify() {
…
}
return{
init:init,
change:change
}
}();
module.exports = exports = myNameSpace;
This way init
and change
will be public
and verify will be private.
You can see Douglas Crockford style of making private members. http://javascript.crockford.com/private.html
Edit
Douglas Crockford's link has been changed now.
new link http://crockford.com/javascript/private.html