Javascript – What are the benefits of using new over closures

closuresjavascript

I've been programming in JS for over a year now, mainly in angularJS. And I can honestly say I've never made a function use prototypical inheritance. When ever i need a class like object that has private data, I use the factory pattern and closures to create classes. I can honestly say I've never needed to use the this key word.

I'm trying to learn node, and it uses prototypical inheritance pretty heavily so it seems. So there has to be a pretty big benefit of using it over closures. Can someone explain the main advantages of using prototypes and what not?

Best Answer

Aside from being more familiar to C++/Java programmers, the only advantage I can think of is that prototypes and constructors have arguably better support for traditional OOP-style inheritance.

Imagine you have class A with method foo(), and class B with method bar() that calls foo(). We want class B to be derived from A, so that it can simply call foo() directly and everything works. With constructors and prototypes, this is easy:

var A = function() {
    this.x = 42;
};
A.prototype.foo = function() {
    return this.x;
};

var B = function() {
    this.y = 7;
};
B.prototype = new A;
B.prototype.constructor = B;

B.prototype.bar = function() {
    return this.x * this.y;
};

var a = new A;
var b = new B;
console.log(a.foo()); // 42
console.log(b.foo()); // 42
console.log(b.bar()); // 294

With closures, you can use the "mixin" approach for public members and methods, but for privates you're basically stuck.

var A = function() {
    var x = 42;
    return {
        foo: function() {
            return x;
        }
    };
};

var B = function() {
    var y = 7;
    var obj = {
        bar: function() {
            return x * y;
        }
    };

    // mix in A's public members
    var a = A();
    Object.keys(a).forEach(function(key) {
        obj[key] = a[key];
    });
    return obj;
};

var a = A();
var b = B();
console.log(a.foo()); // 42
console.log(b.foo()); // 42
console.log(b.bar()); // Uncaught ReferenceError: x is not defined

As far as I can tell, the only way to make this snippet work is to make x public and use "this.x", at which point it might as well not be using closures anymore. Closures can implement "private" access, but not "protected" access, so if you want to do traditional inheritance you have to leave everything public anyway.

Of course, if you don't do very much inheritance, this is a non-issue. At my job we hardly ever inherit from anything, so we also use closures by default.