A class I'm writing in node.js is as below:
module.exports = exports = function(){ return new ClassA() };
function ClassA(){
this.myvariable = 0;
}
I have a function that I want to be private. To my understanding if the function is declared outside of the constructor, it will essentially be a static function which wouldn't be able to reference this.myvariable.
Is the correct way of dealing with this to declare the function within the constructor like this:
//within constructor
this.myFunction = function myFunction(){
console.log(this.myvariable)
}
Or is there a better way of doing it that doesn't leave me with a potentially huge constructor?
EDIT: It looks like I've misunderstood something here because the above code doesn't even work...
JavaScript allows you to define private methods for instance methods, static methods, and getter/setters. The following shows the syntax of defining a private instance method: class MyClass { #privateMethod() { //... } }
In a JavaScript class, to declare something as “private,” which can be a method, property, or getter and setter, you have to prefix its name with the hash character “#”.
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.
Class fields are public by default, but private class members can be created by using a hash # prefix. The privacy encapsulation of these class features is enforced by JavaScript itself.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With