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.
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.
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())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.