Reputation: 59
So I wrote this String function to add stuff to each word in a sentence
String.prototype.addStuff = function() {
return this.replace(/ /g, "-stuff ") + "-stuff"
}
I was told there was a way to invoke this function on a string without using parentheses. Anyone know how?
I tried wrapping the function declaration in parentheses and adding a pair to the end:
String.prototype.liu = (function() {
return this.replace(/ /g, "-liu ") + "-liu"
})();
But that didn't work :/
Upvotes: 1
Views: 2154
Reputation: 816462
You can, with Object.defineProperty
and providing an accessor descriptor:
Object.defineProperty(String.prototype, 'liu', {
get: function() {
return this.replace(/ /g, "-liu ") + "-liu"
}
});
"foo".liu
Although I don't know why you'd want to do that.
Upvotes: 6
Reputation: 3750
function
into a prototype
to auto call.Now, what you can do, is define a shared function
within that prototype
.
Of course, you have to call it, but that beats no answer at all.
Good Read on how prototypical inheritance works
Now, you COULD do:
yourFunc.prototype.call('yourFunc');
But you'd have to format it properly to make it work.
Upvotes: 0