1

I am trying to override a toString() method, but getting into difficulties. Already looked here and here, but still no luck.

My code is as follows:

var Foo = function(arg) {
    // some code here...

    return function (a, b, c) {
       // return function code...
    };
};

Foo.prototype.toString = function () {
    return "string representation of function";
};

exports.bar(arg) {
    return Foo(arg);
};

In another module:

var mod = require('the-module-from-above');
console.log(mod.bar().toString()); // prints return function source code.

My question is, how come my toString() function isn't called, and how can I make it get called?

thank you.

Community
  • 1
  • 1
shimonb89
  • 308
  • 1
  • 8
  • `Foo` is not a constructor in your code, and when `return`ing an object the prototype will be ignored anyway. – Bergi Jan 25 '15 at 22:14

1 Answers1

1

You only set things on a function's prototype if you're using the function as a constructor with new. Since you don't appear to be doing that here, you need to set the toString function on the actual function you return.

function fooToString() {
    return "string representation of function";
}

var Foo = function(arg) {
    // some code here...

    var ret = function (a, b, c) {
       // return function code...
    };
    ret.toString = fooToString;
    return ret;
};

You could also add the toString function when you actually create the object in the bar function, if you'd prefer to do that.

exports.bar(arg) {
    var foo = Foo(arg);
    foo.toString = fooToString;
    return foo;
};
Alexis King
  • 43,109
  • 15
  • 131
  • 205