Freewind
Freewind

Reputation: 198218

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?

Upvotes: 4

Views: 733

Answers (2)

Blender
Blender

Reputation: 298166

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();

Upvotes: 10

dku.rajkumar
dku.rajkumar

Reputation: 18568

you have to write like :

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

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

fiddle : http://jsfiddle.net/PNLxb/

Upvotes: 4

Related Questions