Search code examples
javascriptself-invoking-function

Why does accessing a private variable in another closure's scope via prototypical inheritance allowed?


So I was able to access a private variable (numb) accidentally via prototypical inheritance. I have a couple of questions:

  1. Shouldn't these private variables in a self-invoking anonymous function (SIAF) closure have expired already after the SIAF finished executing? I was expecting it to error out because of 'use strict'.

  2. If it's meant for the variable to never expire, Should this be avoided as part of best practice?

Here's the code:

'use strict';

var GLOBAL = {};


// SELF-INVOKING ANONYMOUS FUNCTION
(function(){

    var numb = 110;
    var Person = function(first_name, last_name) {
        this.name = first_name + ' ' + last_name;
    };

    Person.prototype.getNumb = function() { return numb; };

    GLOBAL.Person = Person;
})();


// ANOTHER SELF-INVOKING ANONYMOUS FUNCTION
(function(){
    function Animal(type_of_animal) {
      this.type = type_of_animal; 
    }

    Animal.prototype = Object.create(GLOBAL.Person.prototype);
    GLOBAL.Animal = Animal;
})();



var dog = new GLOBAL.Animal('dog'); 
console.log( dog.getNumb() ); // This logs 110 to the console.

Here's the fiddle: http://jsfiddle.net/6w2L1y5w/1/


Solution

  • Variable scope in Javascript is lexical. That means, the scope is exactly as written in the source. The function getNumb is defined in the same lexical scope as the variable numb and its body is referring to that variable (return numb). It doesn't matter how or from where you call that function. This is how closures work.

    In fact, this is how "privileged accessors" are implemented in Javascript: you have one "private" variable and one "public" function which has access to that variable through the scope it's defined in.

    (I'm using a lot of "quotes" around "private" and "public" here since those are traditional OOP visibility concepts which only vaguely transfer to Javascript. Javascript has simple lexical variable scope, period. "Privacy" and such is just applying this scoping mechanism in certain patterns to emulate class based OOP semantics.)