Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Just curious how to subclass the String object. (prototypically)

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. ​

like image 704
Todd Vance Avatar asked Oct 03 '12 20:10

Todd Vance


2 Answers

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.

like image 75
Peter Olson Avatar answered Oct 22 '22 04:10

Peter Olson


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());
like image 42
gion_13 Avatar answered Oct 22 '22 03:10

gion_13