Home

Noppanit

09 May 2012

Javascript prototype alternative.

I guess everybody is familiar with the concept of classes in Javascript. For example,

var Adder = function() {
   this.a = "0";
   this.b = "0";
}

Adder.prototype = {
   add : function(value1, value2) {
       return value1 + value2;
   }
}

var adder = new Adder();
adder.add(1,2);

This type is fine in most cases, but the downside of this pattern is that you’re exposing add function to the outside world via prototype, and it’s not good for object-oriented concept. You could easily tamper with function add by doing this.

adder.__proto__.add = function() { };

And if you run this

adder.add(); // undefined

You will get an error because you’ve tampered with function add already.

In order to prevent this to happen you could do something like this. Like this we’re exposing just the function but not via prototype.

var Adder = function() {
    function add(value1, value2) {
        return value1 + value2;
    }

    return { 
        add : add
    };
}

var adder = Adder();
adder.add(1,2); // 3

Reference: http://nodetuts.com/tutorials/28-javascript-classes-prototypes-and-closures.html

Til next time,
noppanit at 00:00

scribble