Reputation: 51
Can anyone please tell me how do we use or declare private members in javascript.I will appreciate an example.I am new to this
Upvotes: 5
Views: 2966
Reputation: 349946
The (currently draft) ECMAScript 2022 Specification includes the concept of private identifiers. See Private class features on MDN:
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.
Most popular JS engines already support it.
Example:
class Animal {
#owner;
constructor(name, owner) {
this.name = name;
this.#owner = owner;
}
hasOwner() {
return Boolean(this.#owner);
}
}
let dog = new Animal("blacky", "trincot");
console.log(dog.hasOwner()); // true
console.log("#owner" in dog, "#owner" in Animal.prototype); // false, false
Upvotes: 1
Reputation: 31
You can try this https://www.npmjs.com/package/private-members
This package will save the members by instance.
const pvt = require('private-members');
const _ = pvt();
let Exemplo = (function () {
function Exemplo() {
_(this).msg = "Minha Mensagem";
}
_().mensagem = function() {
return _(this).msg;
}
Exemplo.prototype.showMsg = function () {
let msg = _(this).mensagem();
console.log(msg);
};
return Exemplo;
})();
module.exports = Exemplo;
Upvotes: 1
Reputation: 9649
here is one way to do it:
function TheClass() {
var _this = this;
var privateMember = 'foo';
this.publicMember = 'bar';
var privateMethod = function(){
// things happen here
};
this.publicMethod = function(){
//other things here
_this.publicMember = 'sparky';
return privateMember;
};
}
var myObj = new TheClass();
alert(myObj.privateMember); //won't work
alert(myObj.publicMember); //should work
alert(myObj.publicMethod()); //should work too
see this working fiddle and play a bit with it ;)
Upvotes: 4
Reputation: 94101
JavaScript doesn't have private variables per-say. In JS variables are scoped to the top of the closest function. So creating a function (or closure) is a way to make private variables only accessible within that scope. The important thing to remeber is to always use var
to declare variables, otherwise, even inside a function, the variable will become global, and that's bad.
If you're working with prototype inheritance then it's as easy as creating a constructor and any variable declared with var
will be private and declared with this
will be public.
function Bar() {
var foo = ''; // private
this.baz = function() {}; // public
}
var bar = new Bar(); // create new instance of Bar
alert(bar.foo); // error
alert(bar.baz); // function
Also the above constructor is very simple, typically you'd put function methods on the actual prototype
of the object, like Bar.prototype.baz = function(){}
.
If you're working with a singleton for example, you can use the module pattern:
var bar = (function(){ // bar is public
var foo = ''; // foo is private
function baz() {}; // baz is private
return {
baz: baz // expose 'baz' as a public member of 'bar'
}
}());
alert(bar.foo); // error
alert(bar.baz); // function
Upvotes: 1
Reputation: 8767
Douglas Crockford has a write-up on Private Members:
Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.
function Container(param) {
this.member = param;
var secret = 3;
var that = this;
}
This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
}
The private method dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can be used to make this object limited to three uses.
By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.
Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.
Upvotes: 8
Reputation: 4391
Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.
function Container(param) {
this.member = param;
var secret = 3;
var that = this;
}
This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.
You can find more details on this link.
Upvotes: 0