-1

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.

Lyubomir
  • 19,615
  • 6
  • 55
  • 69
  • What is the purpose of creating an alias for `.length`? Note, `this` with IIFE is not `String` – guest271314 Sep 10 '16 at 23:10
  • 1
    is this kind of homework? There was already a suspiciously similar question from half an hour ago: http://stackoverflow.com/questions/39431230/add-an-alias-for-a-property-in-javascript – VLAZ Sep 10 '16 at 23:11
  • 2
    Possible duplicate of [Javascript getters and setters for dummies?](http://stackoverflow.com/questions/812961/javascript-getters-and-setters-for-dummies) – Siguza Sep 10 '16 at 23:13
  • that's why I'm asking, because I answered on the question you mentioned, but I realised my answer wasn't correct. @Siguza you read my note I hope – Lyubomir Sep 10 '16 at 23:13

2 Answers2

2

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');
'foo'.foo;
'foo'.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.

ruakh
  • 175,680
  • 26
  • 273
  • 307
1

It seems like you are trying to define a getter on String.prototype

Object.defineProperty(String.prototype, 'overEstimatedLength', {
  get: function() {
    return this.length + 12345;
  }
});
console.log('hello'.overEstimatedLength)

Your code doesn't work because it's executing your function immediately and assigning the result of that to String.prototype.overEstimatedLength. That is, it's almost exactly the same as...

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

The following would kind of work, but you'd call it as a function, notice that you are returning a function, so that gets assigned to String.prototype

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

console.log('something'.overEstimatedLength())
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217