Question

What is the difference between this:

Library1 = function () {};
Library1.prototype.myFunc = function (p) {
    function helper1(p) {return p * 2; }
    function helper2(p) {return p * 4; }
    this.result = helper1(p) + helper2(p);
}

and this:

Library2 = function () {};
Library2.prototype.myFunc = function(p) {
    this.result = Library2.helper1(p) + Library2.helper2(p);
}
Library2.helper1 = function(p) {return p * 2; }
Library2.helper2 = function(p) {return p * 4; }

I get the same results either way:

test = new Library1();
test.myFunc(2);
window.console.log(test.result); // 12

test = new Library2();
test.myFunc(2);
window.console.log(test.result); // 12

Is one method preferred over the other?

This post implies that method 1 "pollutes" the prototype: What is the proper way to declare javascript prototype functions calling helper functions.

Do function declarations in a prototype pollute the prototype whereas assigning them seperately is somehow cleaner?

Was it helpful?

Solution

Do function declarations inside a prototype method pollute the prototype?

No, because they are private.

Is assigning auxiliary functions as methods of the constructor cleaner?

No, because this way you pollute the constructor.

Is one method preferred over the other?

If you don't want to pollute objects, better use function declarations inside methods.

The disadvantage of that is that each time you call myFunc, both helper1 andhelper2 must be recreated.

Then, if you don't want to pollute anything and don't want to recreate auxiliary methods each time, you can use

Library1 = (function() {
    function Library1() {}
    function helper1(p) {return p * 2; }
    function helper2(p) {return p * 4; }
    Library1.prototype.myFunc = function (p) {
        this.result = helper1(p) + helper2(p);
    }
    return Library1;
})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top