dark night
dark night

Reputation: 171

how to make private and public variables on node.js

on php I can write variables like that on node.js how to set the variables types

private $varone;


public $varone;

are var varone; in node are the same private $varone; on php ?

Upvotes: 0

Views: 3243

Answers (1)

jfriend00
jfriend00

Reputation: 707796

First off, Javascript does not have private and public modifiers for variables. You will typically control the access to variables by defining or assigning them into an appropriate scope where only code within that scope has access to them.

Node.js programming is typically done with modules. Each module gets it's own scope so any variables defined within the module are only available to code within that module.

To share something with other modules, one would typically export the variable or function or method so that anyone importing the module could get access to it. Or (though this is rarely the best way to do things), you can assign variables as properties on the global object and then all code within that node.js process can access it via the global object.

So, a typical node.js module might look like this:

// mymodule.js

function doSomething(a, b) {
    return a + b;
}

let total = 0;

function doSomethingElse(c, d) {
    total += c * d;
}

// other code here that calls doSomethingElse()

module.exports = doSomething;

So, in this module, all variables and functions are, by default, private to the module. So, doSomethingElse and total are private to the module. The function doSomething is specifically exported so anyone loading the module can get access to that function.

var doIt = require('./mymodule.js');

console.log(doIt(3, 4));    // 7

Within a module, you can also create your own functions that can create sub-scopes to further restrict access even within a module.

Upvotes: 4

Related Questions