Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 604
NoPyGod Avatar asked Dec 03 '22 00:12

NoPyGod


1 Answers

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());  
like image 96
JaredPar Avatar answered Dec 04 '22 14:12

JaredPar