leo leo - 1 year ago 61
Javascript Question

JavaScript - prototype as a self invoking function (IIFE)

I would like to define a prototype on String that is a self-invoking function

String.prototype.overEstimatedLength = (function() {
return this.length + 12345

and then use it like this

'hello world'.overEstimatedLength

Unfortunately, this doesn't work. Is something like that syntactically possible and why is the example above not working?

Note: I know that property definition would be more appropriate (such as a Getter), I'm specifically interested in self-invoking functions.

Answer Source

The problem with your example is that there isn't actually such a thing as a "self-invoking function", only an "immediately-invoked function expression", with the emphasis on immediately.

Consider something like this:

String.prototype.foo = alert('foo');

This runs alert('foo') immediately, then stores the result in String.prototype.foo . . . and then just retrieves that result a few times (doing nothing with it). So 'foo' will get alerted only once.

Your example is similar; you are immediately invoking your function expression.