I cannot extend 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 can’t understand why. I extended the Array prototype without any problems.

+4
source share
1 answer

The code you showed correctly extends the String prototype. However, you are trying to call a method for a function with String.testthing , not a String instance.

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

If you really want to call methods from the String construct, you need to extend the prototype to Function

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

Source: https://habr.com/ru/post/1380464/


All Articles