Search code examples
javascriptprototype-programming

I can't extend the String prototype in javascript


Here is the code

<script>

String.prototype.testthing = function() {
    return "working";
}

alert(String.testthing());

</script>

When I open this page I get the error below

Uncaught TypeError: Object function String() { [native code] } has no method 'testthing'

I cannot figure out why. I've extended the Array prototype with no issues.


Solution

  • The code you've shown correctly extends the String prototype. However you're trying to call a method on a function with String.testthing and not on a string instance.

    alert("".testthing());  // "displays 'working'
    

    If you actually want to call methods off of the String construct then you need to extend the prototype on Function

    Function.prototype.testthing = function () { 
      return "working";
    }
    alert(String.testthing());