Understanding public/private instance variables - javascript

I am reading a tutorial on public/private methods and can't make sense of the difference.
For a private method it says, "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;
}
And for public methods, "this technique is usually used to initialize public instance variables. The constructor's this variable is used to add members to the object."
function Container(param) {
this.member = param;
}
As you can see both functions have a params paramater and a this.member = param;. Yet one is a private instance variable and the other is a public instance variable?

Understanding closures
Opening a new function body creates a new scope. This kind of scope is called a closure in JS. Variables created within that scope are accessible in all its sub-scopes. This means any var-created variable will be made visible to sub-functions. In this example, myTemporaryVar is accessible within subScope.
function myParentScope() {
var myTemporaryVar = "sample";
function subScope() {
console.log(myTemporaryVar);
}
return subScope();
}
When you use a function with the new keyword, a new closure is created for the current instance. Any function created within that constructor will keep access to the scope variables. In the next example, the function sayHi can access the temporary variable myName.
function Person(name) {
var myName = name;
this.sayHi = function() {
console.log("Hi, my name is " + myName + ".");
};
}
p = new Person("Bob");
p.sayHi(); // Hi, my name is Bob.
Actually, passed parameters are the same as var-created variables. The constructor's parameters are accessible within any sub-function. So the previous example can be reduced to:
function Person(name) {
this.sayHi = function() {
console.log("Hi, my name is " + name + ".");
};
}
p = new Person("Bob");
p.sayHi(); // Hi, my name is Bob.
This is a very unique feature of JavaScript because it means var-created variables still exist after the end of the function as long as there still is a way to access them.
Simulating Class-based OOP privacy
Closures can be "abused" to create private members with getter and setter functions.
function Person(name) {
this.getName = function() {
return name;
};
this.setName = function(newname) {
name = newname;
};
}
p = new Person("Bob");
console.log(p.getName()); // "Bob"
p.setName("Alice");
console.log(p.getName()); // "Alice"
p.name; // undefined
Why this is not true privacy
The getter and setter have to be created within the constructor in order to access the var-variable. Methods added in the common prototype-extension way can't access them. Prototype-methods have to use the setters and getters too, which makes the privacy of such variables quite useless.
Person.prototype.sayGoodMorning = function() {
console.log("Good morning, my name is " + this.getName() + ".");
}
The only way to directly access the variable within a method is to actually create it in the constructor. But putting all methods inside the constructor is extremely inefficient as a new copy of the methods will be created for each instance. This is why many people prefer simply using custom notation to identify would-be private members. The Google JavaScript Style Guide recommends placing an underscore at the end of the variable name.
function Person(name) {
this.name_ = name;
}
Person.prototype.getName = function() {
return this.name_;
}
Person.prototype.setName = function(name) {
this.name_ = name;
}
Person.prototype.sayGoodMorning = function() {
console.log("Good morning, my name is " + this.name_ + ".");
}
It is the responsibility of the programmer to not be stupid and access the would-be private members. Note that this goes in total contradiction with Crockford's opinion, but to each is own. I learned JS after Python, so the underscore privacy is like a second nature to me.

No one of this variable is trully private because if you instanciate Container you can access to secret variable :
function Container(param) {
this.member = param;
var secret = 3;
var that = this;
}
var container = new Container();
console.log(container.secret);
container.secret = "toto";
console.log(container.secret);
console.log(container);
Here the result :
As you can see you can access to secret without any "Getter/Setter".
If you want to do object javascript with truly private variable, look at this tutorial :
http://blog.stchur.com/2011/09/26/true-private-variables-in-javascript-with-prototype/

Related

javascript: can I define a "private" variable using prototype?

I want to use a unique private variable for each "instance" (I hope that this is the right term in Javascript), but both instances appear to use the same private variable.
func = function(myName)
{
this.name = myName
secret = myName
func.prototype.tellSecret = function()
{ return "the secret of "+this.name+" is "+secret
}
}
f1 = new func("f_One")
f3 = new func("f_3")
console.log(f3.tellSecret()) // "the secret of f_3 is f_3" OK
console.log(f1.tellSecret()) // "the secret of f_One is f_3" (not OK for me)
I saw a solution but
this would mean duplicating the function on every instance, and the
function lives on the instance, not on the prototype.
Another author says about the same solution
That's still not quite traditional classly Javascript, which would define the methods only once on Account.prototype.
So, is there a solution where
every instance can have unique values for secret
secret is only accessible for methods that are defined in the constructor
and
functions are not duplicated for every instance
?
The problem is that you're replacing your prototype function each time the constructor is called.
With old-style closure-based privacy, you can't access "private" members from prototype methods, because only functions defined in the constructor closing over them can use them. So you end up remaking the functions for each instance (which isn't as bad as it sounds, but isn't great).
function Example(name) {
this.name = name;
var secret = name; // Using `var` here on the basis this is ES5-level code
// This can't be a prototype function
this.tellSecret = function() {
return "the secret of " + this.name + " is " + secret;
};
}
Two options for you:
1) Use a transpiler like Babel, class syntax, and private fields (likely to be in ES2021, in use for a fair bit time now via transpiling):
class Example {
#secret;
constructor(name) {
this.name = name;
this.#secret = name;
}
tellSecret() {
return "the secret of " + this.name + " is " + this.#secret;
}
}
const f1 = new Example("f_One");
const f3 = new Example("f_3");
console.log(f3.tellSecret()) // "the secret of f_3 is f_3"
console.log(f1.tellSecret()) // "the secret of f_One is f_One"
2) Use a WeakMap (ES2015+) containing the secret information
const secrets = new WeakMap();
class Example {
constructor(name) {
this.name = name;
secrets.set(this, name);
}
tellSecret() {
return "the secret of " + this.name + " is " + secrets.get(this);
}
}
const f1 = new Example("f_One");
const f3 = new Example("f_3");
console.log(f3.tellSecret()) // "the secret of f_3 is f_3"
console.log(f1.tellSecret()) // "the secret of f_One is f_One"
You put secrets where only Example has access to it.
You can use a WeakMap without using class syntax too, but if you're creating constructor functions with associated prototypes, class is simpler than function Example and assigning to properties on Example.prototype.

JavaScript Module Pattern - Private variables vs. Static variables

So this is an example of the famous JavaScript Module Pattern:
var Person = (function() {
var _name; // so called 'private variable'
function Person(name) {
_name = name;
}
Person.prototype.kill = function() {
console.log(_name + ' has been shot');
};
return Person;
})();
var paul = new Person('Paul');
paul.kill();
So far so good right? This logs 'Paul has been shot' to the console, which is what we want.
But.
Is _name really a private variable? I would define a private variable as a variable that belongs to an instance of an object, which is not accessible for the outside world. The last part works, I can not access _name from outside the closure.
But if I do this:
var paul = new Person('Paul');
var bran = new Person('Bran');
paul.kill();
bran.kill();
This will then log 'Bran has been shot', twice. No Paul there. So _name is actually shared with all instances of my Person object. That's what I would define as a 'static variable', although it's also not accessible from outside.
So is there any way to create a real private member variable with the module pattern? One that is not static.
Something that also happens a lot is defining this._name inside the constructor function, but that kills the private part, it's now accessible from outside:
function Person(name) {
this._name = name;
}
var bran = new Person();
console.log(bran._name); // yep, accessible
Question:
So. Private is not really private, just static. How do we create a real private member variable with the module pattern? A variable which belongs to an instance, which is not static, and a variable which is not accessible from the outside.
You're right; _name is more of a static variable. It is kept in the closure that contains the constructor, so every use of the constructor will use that same variable. And remember, this has nothing to do with classes, and everything to do with closures and functions. It can be pretty handy, but it isn't how you do private members.
Unsurprisingly, Douglas Crockford has a page devoted to private members in Javascript.
In order to make private members, you have to go 'one level deeper'. Don't use a closure outside of the constructor; use the constructor as the closure. Any variables or methods defined inside the constructor are obviously not usable by the outside world. In fact, they aren't accessible by the object, either, so they are rather extremely 'private'.
We want to use our private members though. :) So what to do?
Well, in the constructor, do this:
var Klass = function () {
var private = 3;
this.privileged = function () { return private; };
};
and then:
var k = Klass();
console.log(k.privileged()); // 3
See how that's using the constructor as a closure? this.privileged lives on, attached to the object, and thus private lives on, inside this.privileged's closure.
Unfortunately, there's one problem with private and privileged methods in Javascript. They must be instantiated from scratch each time. There is no code sharing. That's obviously what we want with private members, but it isn't ideal for methods. Using them slows down object instantiation and uses more memory. It's something to keep in mind when/if you run into efficiency problems.
"Real private member variables" and prototype based methods do not play nice together. The only way achieve what you want is to create all methods in the constructor.
var Person = (function() {
function Person(name) {
this.kill = function() {
console.log(name + ' has been shot');
};
}
return Person;
})();
var paul = new Person('Paul');
var bran = new Person('Bran');
paul.kill(); // Paul has been shot
bran.kill(); // Bran has been shot
But this will use more memory and be slower since each instance has a unique version of the kill function.
Conventionally, the underscore prefix is used for semi-private instance properties, as long as the data exposed is not a security risk. Most consumers of your javascript code know not to mess with underscore prefixed properties.
Some more reading you may find useful is here.
The problem is that your _name variable is outside the Person scope and shared between all Person instances. Do something like the following instead :
(function() {
var Person = function(name) {
var _name = name; // so called 'private variable'
this.getName = function()
{
return _name;
}
this.kill = function()
{
console.log(this.getName() + ' has been shot');
}
}
/*Alternative
Person.prototype.kill = function() {
console.log(this.getName() + ' has been shot');
};*/
window.Person = Person;
})();
var paul = new Person('Paul');
var bran = new Person('Bran');
paul.kill();
bran.kill();
A variable that needs to be private in instance scope has to be in such scope, for example:
function Person(name) {
var _name = name;
this.kill = function() {
console.log( _name + ' has been shot' );
}
}
A drawback of this is that kill has to be defined in a scope that also has access to the private variable.
In order to create a private var, you should put it inside the constructor, so your code would be like this:
var Person = (function() {
function Person(name) {
// since name is a param, you don't even have to create a _name var
// and assign name to it
this.getName = function () {
return name;
};
}
Person.prototype.kill = function() {
console.log(this.getName() + ' has been shot');
};
return Person;
})();
var paul = new Person('Paul');
paul.kill();
You can also declare .kill inside the constructor:
var Person = (function() {
function Person(name) {
this.kill = function() {
console.log(name + ' has been shot');
};
}
return Person;
})();
var paul = new Person('Paul');
paul.kill();

JavaScript Object.prototype Access Private Values

I've read that using Object.prototype to attach functions to custom JavaScript objects is more efficient than the "traditional" method of this.foo = function(). The problem I've run into is scope. I want these public methods to be able to access private variables of the object. What I ended up doing was this:
function Foo(){
var id = 5;
Foo.prototype.bar = function(){
alert(id);
};
}
var x = new Foo();
x.bar();
I nested the prototype declaration inside the object definition. This works and seems to solve the problem. Is there any reason to NOT do this? Is there a better or more standard way to accomplish this?
UPDATE
Based on some of the responses I've received I guess I need to mention that I'm fully aware that there is no concept of a private variable in JavaScript. I use the term private here meaning not accessible outside the current scope because it's easier to say and write and I assume that anyone trying to answer this question would know what was meant by me using the term private.
While your idea works, it may not be working as you expect. I believe your overwrites the prototype each time a new Foo is instantiated. It would potentially change the bar() method for all instances of Foo each time you create a new Foo. Oops.
Here's an example of using fake private variables for someone to "lie" about their real age.
Here is the standard way to do this:
function Person(name, age) {
this._age = age; // this is private by convention only
this.name = name; // this is supposed to be public
}
Person.prototype.sayHiTo = function(person) {
console.log("Hi " + person.name + ", my name is " + this.name);
}
Person.prototype.age = function() {
return this._age - 3;
}
var j = new Person("Jay", 33);
var k = new Person("Kari", 26);
j.sayHiTo(k) // Hi Kari, my name is Jamund
k.age(); // 23
You can use privileged methods to access the private members.
More info here: http://javascript.crockford.com/private.html
However, IMO it's really not worth it. It's cumbersome and it cripples classical inheritance.
And for what? To "shield" users from accessing your private members directly?
It's JS, they have the source and the means to access them anyway, it's really not worth the effort. Underscoring pseudo private members is enough.
There is no private in JavaScript, just do things properly
var Foo = {
bar: function () {
console.log(this._id)
},
constructor: function () {
this._id = 5
return this
}
}
var x = Object.create(Foo).constructor()
x.bar()
here how you can fake it. This is Animal class
(function(window){
//public variable
Animal.prototype.speed = 3;
//public method
Animal.prototype.run = function(){
//running
}
//private method
//private method
function runFaster(){
//run faster
}
//private var
//private var
var legCount = 4;
}(window));

Is there anyway to have instances share the same function yet at the same time have private variables?

I have this piece of code:
var Human=function(name){
this._name=name;
};
Human.prototype.Shout=function(){
alert(this._name);
};
var tom=new Human("tom");
var john=new Human("john");
alert(tom.Shout===john.Shout);
Right now ._name is not "private". I want to make ._name "private", but at the same time i do not wish to create additional functions for each instance of Human (in other words tom.Shout Must be === to john.Shout) because creating additional functions for each instance is just well.. unnecessary (ok offtopic - we can debate this on another thread)
My conclusion is that what I'm trying to achieve (having ._name be "private" and at the same time having tom.Shout===john.Shout) is impossible.
But I just want to be 200% sure before jumping into any conclusions.
(I welcome any hacks as long as the requirements are met, i.e no creating of additional functions for each instance)
If we have to create additional functions to do scoping that's fine but that number should be a fixed number and that number should not increase with each additional instance of Human.
Update
Your looking for #name which is an instance variable. Pray it's in es.next, but we don't have it yet. Maybe in two years.
If you care about a clean API then here is your solution:
function Class(foo) {
Class.priv(this).foo = foo;
}
Class.priv = (function() {
var cache = [],
uid = 1;
return function(obj) {
if (!this.__id) {
this.__id = uid;
cache[uid++] = {};
}
return cache[this.__id];
};
}());
Class.prototype.bar = function() {
console.log(Class.priv(this).foo);
}
Store all the data in a cache as a function of the constructor. No data is cluttered on the object.
Original
However there is no such thing as "private".
All you can do is create a local variable inside a function.
The constructor function
var Human = function(name) {
// local variable.
var _name = name;
}
Has a local variable that by very definition of being local is not usable outside of the constructor function.
This means that you cannot access it in external code like the prototype.
What you can do however is make it read only using ES5
var Human = function(name) {
Object.defineProperty(this, "name", { value: name });
}
If you can truly achieve what your asking, you'd make a huge breakthrough in js. I've attempted to do just that for many hours.
A different pattern would be :
var Human = function(name) {
this.name = name;
return {
Shout: this.Shout.bind(this)
};
}
Human.prototype.Shout = function() {
console.log(this.name);
}
This has the overhead of calling .bind and creating a new object for every instance though.
how about this ?
var Human = function (name) {
var _name = name;
this.getName = function () {
return _name;
}
};
Human.prototype.Shout = function () {
alert(this.getName());
};
var tom = new Human("tom");
var john = new Human("john");
tom.Shout(); // tom
john.Shout(); // john
alert(tom.Shout === john.Shout); // true
EDIT:
the former creates another function for GET property,
it is not possible without creating additional functions.
Did read the question, didn't understand, because this._name is just not private, so the question is a bit weird. This is how in my test the prototype methods are added once and available to all instances. I repeat: this._name is not private here. If you add a local variable, and want to access it via a closure in a prototype method, calling the value of the local variable will result in the same value for all instances.
Anyway, with this constructor function the this._name getter and shout methods are added to the prototype chain once and thereby available for all instances of Human.
function Human(name) {
if (!(this instanceof Human)){
return new Human(name);
}
this._name = name;
if (!Human.prototype.Name){
Human.prototype.Name = function(val){
if (val){
this._name = val;
return this;
}
return this._name;
};
Human.prototype.shout = function(){
alert(this._name);
}
}
}

why make non-privileged methods?

I'm learning JavaScript, and I can't understand why you'd make methods that aren't 'privileged,' that is, that aren't defined in the constructor but rather the class' prototype.
I understand the idea of encapsulation and all, but you never encapsulate parts of a class from the rest of it in most of the OO world.
When a function is defined in a constructor, a new instance of that function is created each time the constructor is called. It also has access to private variables.
var myClass = function() {
// private variable
var mySecret = Math.random();
// public member
this.name = "Fred";
// privileged function (created each time)
this.sayHello = function() {
return 'Hello my name is ' + this.name;
// function also has access to mySecret variable
};
}
When a function is defined on the prototype, the function is created only once and the single instance of that function is shared.
var myClass = function() {
// private variable
var mySecret = Math.random();
// public member
this.name = "Fred";
}
// public function (created once)
myClass.prototype.sayHello = function() {
return 'Hello my name is ' + this.name;
// function has NO access to mySecret variable
};
So defining a function on the prototype produces less objects which can give you better performance. On the other hand, public methods do not have access to private variables. Further examples and reasoning are available here: http://www.crockford.com/javascript/private.html

Categories