Why does "String.prototype = {}" not work?

I wrote this code in javascript:

String.prototype = { a : function() { alert('a'); } }; var s = "s"; sa(); 

I expect him to warn a , but he reports:

 sa is not a function 

Why?

+4
source share
2 answers

It seems you are replacing the whole prototype object with String with your object. I doubt it will even work, not to mention your intentions.

The prototype property is not writable, so assignments to this property silently fail (@ FrΓ©dΓ©ric Hamidi).

Using regular syntaxes works:

 String.prototype.a = function() { alert('a'); }; var s = "s"; sa(); 
+10
source

you need to write:

 String.prototype.a = function(){ alert("a"); }; var s = "s"; sa(); 

script: http://jsfiddle.net/PNLxb/

+4
source

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


All Articles