5

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

6 Answers 6

8

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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 ;)

7 Comments

Can you please explain your code,how this has made members private ?
privateMember and privateMethod() are accessable from Members of an instance of the class. publicMember and publicMethod() can be called from outside the class-scope. I`ll edit my answer to illustrate what i mean...
i've also added a example of realizing a way to implement classvars, also if many people are a bit sceptical about that. thee the fiddle referenced in the answer for that...
But I can still modify the value of your private field... myObj.privateMember = "modified";
You could do so even if there was no such property in advance. You wouldnt modify, you'd add the property. Try it with any other prop. It will always work.
|
1

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 

1 Comment

Thanks man....add me on skype or facebook or gmail..lol nirjhar18 at skype and gmail. can you tell me some interview questions for javascript..i hav it tomorrow..wt shld i cover
1

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; 

Comments

1

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

Comments

0

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.

2 Comments

I have read that man..but how are these private now..you declare public also in the same way..this is the link you get
@AndroidHelp - They are private because they cannot be accessed outside of the function, without declaring them in the global scope first and not re-declaring them using var.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.