Reputation: 198218
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
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
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