Renato Zannon
Renato Zannon

Reputation: 29941

Should I worry when overriding function.toString in JavaScript?

When I write function wrappers in JavaScript (for example: a throttle or debounce function), I would like to be able to inspect the 'decorated' function and still be able to know what is the underlying function. Take an implementation of throttle for an example:

function throttle(fn, time) {
  var handle;

  var execute = function() {
    handle = null;
    fn.apply(this, arguments);
  };

  var throttled = function() {
    if(!handle) {
      handle = setTimeout(execute.bind(this), time);
    }
  };

  throttled.toString = function() {
    return fn.toString() + "\n// throttled to " + time + "ms";
  };

  return throttled;
}

var makeAjax = throttle(function(callback) {
  $.getJSON("/path", callback);
}, 500);

console.log(makeAjax);

The console.log call displays:

function (callback) {
  $.getJSON("/path", callback);
}
// throttled to 500ms

As a user of throttle I care a whole lot more about the function I gave it than its internal throttled.

However, I always feel a little uneasy while overriding native functions. Are there any compliance and/or performance issues that I should worry about when doing this?

Upvotes: 2

Views: 369

Answers (1)

Eric
Eric

Reputation: 733

In Mozilla Developer Group, they talk more about overriding toString(). https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/toString

I think what could be a possible issue here is creating the automated Unit-Test (my experience is limited to NUnit Selenium), you may not able to use the private .toString() or it might cause unstable test results? also debugging might be an issue!

For overriding other local js functions that has methods, you might need to manually extend all of the methods as well to replace what's been overriden.

Addy Osmani discusses this further in his book "Learning JavaScript Design Patterns", http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

Upvotes: 3

Related Questions