Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

Prototypes can't talk to local variables in the constructor

You can create local variables via a closure but then you'd have problems with inheritance.

    var counter = function () {
      var count = 0;
      this.increment = function () { count++; }
      this.get = function() { return count; }
    }
    //now
    counter.prototype.decrement = function () {
       count--; //will be undefined :)
    }

Well, this might not seem weird unless you compare it with some other programming language where Object Orientation is proper and true.

    class counter {
    private: int count;
    public:
      void increment() { count++; }
      void decrement();
    }
    void counter::decrement { count--; } //count is not undefined.

JavaScript is not a queer creature. There is no actual OOP in the language. The scope is what that helps us in simulating Object Orientation. Well, to make that work with JavaScript, you could use something like,

    var counter = function () {
      this.count = 0;
      this.increment = function () { count++; }
      this.get = function() { return count; }
    }
    //now
    counter.prototype.decrement = function () {
       this.count--; // yes, you have to use `this` in javascript a lot!
    }

    // using the "class"
    c = new counter();
    c.decrement();
    console.log(c.count); // -1

Keep in mind that, certain aspects won't be enforced by the language itself, but instead provided as a syntactic sugar. The bottom line is that, when you write some code that plugs into a browser, you need not worry about protecting variables from the user. He can anyway peep in and do nasty things if he wishes. This might be a concern in environments like NodeJS.