Is it possible to copy a primitive like String so it can be extended only in the current function?
var foo = function() {
var String = // somehow clone String (the primitive function)
String.prototype.first = function() { return this.charAt(0) };
return 'abc'.first();
}
foo(); // returns 'a'
'abc'.first(); // returns TypeError "abc".first is not a function
The solution must either copy the primitive which doesn't seem possible, or destroy the new method after the function is complete...
String is a global and if you change it or add to its prototype, then the changes are by definition global. So to revert the changes, you have to revert them.
Normally one would try to derive a custom subclass and add the new prototype method to it, but built-in types like String are notoriously hard to subclass, and even if you could you'd have to call it with something like MyString('abc').first().
Your problems stem from your misguided notion of augmenting the String prototype. It's never a good idea to pollute prototypes. I understand your idea of dealing with that by somehow removing it real quick after adding it and using it, but that's not realistic, and the setTimeout approach is a horrible, unreliable hack.
However, if you really insist on adding to the String prototype, then one idea is to add all your new instance methods to a single property which is less likely to collide with things. Let's call it Utils. We would want to be able to call
'abc'.Utils.first()
But how can we make this work? We define a getter on the Utils property which returns a hash of the methods. Using a getter (instead of value) provides us with the this, which we can pass along to the methods using bind.
Object.defineProperty(String.prototype, 'Utils', {
get: function() {
return {
first: function() { return this.charAt(0); }.bind(this)
};
}
});
> 'abc'.Utils.first()
< "a"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With