Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the correct way to do private functions in Javascript / node.js?

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...

like image 546
aussieshibe Avatar asked Sep 11 '15 05:09

aussieshibe


People also ask

Can you have private functions JavaScript?

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() { //... } }

How do you write a private function in JavaScript?

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 “#”.

What is the drawback of creating true private in JavaScript?

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.

Does JavaScript have public and private methods?

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.


1 Answers

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()
like image 175
Yuri Zarubin Avatar answered Oct 06 '22 04:10

Yuri Zarubin