Search code examples
javascriptstringthisfunction-prototypes

String.prototype.myFunction not returning a string?


Why does the below code not return this properly? It should just return 'image', rather than all of the letters in an object, shouldn't it?

String.prototype.removeExtension = function(){
    return (this.lastIndexOf('.') !== -1) ? this.substr(0, this.lastIndexOf('.')) : this;
}

'image.jpg'.removeExtension(); // returns 'image'

'image.png.jpg'.removeExtension(); // returns 'image.jpg'

'image'.removeExtension(); // returns String {0: "i", 1: "m", 2: "a", 3: "g", 4: "e", removeExtension: function}

Solution

  • this always references an object within the context of a scope (*). You need to invoke .toString() for instance, to get the pseudo primitive value out of it.

    return this.toString();
    

    If you return this just like that, it'll reference the current instance of that String-object currently invoked.


    (*) (only exception is ES5 strict mode, where this also might reference the undefined value