Javascript Prototype Alternative.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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.

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

And if you run this

1
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.

1
2
3
4
5
6
7
8
9
10
11
12
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

May 9th, 2012

Comments