Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need private variables?

What are they for and how do we make it? Can you give me an example?

like image 489
David G Avatar asked May 26 '26 04:05

David G


2 Answers

To avoid collisions with multiple libraries, for example.

Say they both use a variable commonly used such as data. If both libraries use private variables it's all fine:

var lib1 = (function() {
    var data;

    return {
        get: function()  { return data },
        set: function(v) { data = v }
    };
})();

// Supposed to do something different:
var lib2 = (function() {
    var data;

    return {
        get: function()  { return data },
        set: function(v) { data = v }
    };
})();

lib1.set(123);
lib2.set(456);
lib1.get(); // 123
lib2.get(); // 456

However suppose they don't use private variables but global ones like this:

var lib1 = (function() {
    return {
        get: function()  { return data },
        set: function(v) { data = v }
    };
})();

// Supposed to do something different:
var lib2 = (function() {
    return {
        get: function()  { return data },
        set: function(v) { data = v }
    };
})();

lib1.set(123);
lib2.set(456);
lib1.get(); // 456 - overwritten by lib2. lib1 might not work properly anymore.
lib2.get(); // 456

So lib1.get() will fetch the same data as lib2.get().

This example is too obvious of course but to stay safe it's a good practice to use private variables.

like image 125
pimvdb Avatar answered May 27 '26 17:05

pimvdb


Variables are encapsulated within a class to stop their names colliding. These can be public or private. Sometimes there is a need to make sure that variables are only changed using the functions that set them. For example the parts of a date would need to be verified to stop someone setting an invalid date such aas February 45th.

var factorial = (function(){
    var precog = [1,1];// ===undefined for other indices, N = undefined || N
    return function(y){  
        return precog[y] || (precog[y]=y*arguments.callee(y-1));
    };
})();

Here is a JavaScript function with a private precog. This stores previously calculated values and it is private to stop them being manipulated.

like image 36
QuentinUK Avatar answered May 27 '26 16:05

QuentinUK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!