Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "String.prototype={}" won't work?

I wrote this code in javascript:

String.prototype = {
  a : function() {
    alert('a');
  }
};

var s = "s";
s.a();

I expect it alert an a, but it reports:

s.a is not a function

Why?

like image 349
Freewind Avatar asked Dec 10 '22 03:12

Freewind


1 Answers

You seem to be replacing the entire prototype object for String with your object. I doubt that will even work, let alone be your intention.

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

Using the regular syntax works, though:

String.prototype.a = function() {
  alert('a');
};

var s = "s";
s.a();
like image 68
Blender Avatar answered Dec 11 '22 17:12

Blender