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?
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?
Share Improve this question edited Dec 26, 2011 at 21:51 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Dec 23, 2011 at 8:48 FreewindFreewind 199k163 gold badges452 silver badges736 bronze badges2 Answers
Reset to default 10You 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();
you have to write like :
String.prototype.a = function(){
alert("a");
};
var s = "s";
s.a();
fiddle : http://jsfiddle/PNLxb/