I know this is frowned upon, I was just exploring the idea and for the life of me cannot seem to make this work the way I would want it too.
The example should explain all:
String.prototype.MyNS = function() {}
String.prototype.MyNS.fooify = function() {
return this + 'foo!';
}
var theString = 'Kung';
alert(theString.MyNS.fooify());
Of course this simply append the function definition to 'foo' ... adding this() instead doesnt work.
I understand that I have lost context in there but cannot figure out how to cause the original to fire off and give me what I want.
Here's one way you could do it:
String.prototype.MyNS = function() {
var _this = this;
return {
fooify: function() {
return _this + 'foo!';
}
};
}
See it in action on jsFiddle
Note, as slashingweapon points out, that you will have to call it like so:
String.prototype.MyNS().fooify();
As far as I know, there's no cross-browser way to do it without having to call MyNS
as a function.
You are adding a new function
(class
in oo terms) to the String
prototype
and it has no access to the actual String
instance.
You could just add the property directly to the prototype :
String.prototype.fooify = function() {
return this + 'foo!';
}
var theString = 'Kung';
alert(theString.fooify());
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