[英]Why “String.prototype={}” won't work?
I wrote this code in javascript: 我在javascript中编写了这段代码:
String.prototype = {
a : function() {
alert('a');
}
};
var s = "s";
s.a();
I expect it alert an a
, but it reports: 我希望它提醒a
,但它报告:
s.a is not a function
Why? 为什么?
You seem to be replacing the entire prototype
object for String
with your object. 您似乎正在用您的对象替换String
的整个 prototype
对象。 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 ). prototype
属性不可写,因此对该属性的赋值无声地失败( @FrédéricHamidi )。
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.net/PNLxb/ 小提琴: http : //jsfiddle.net/PNLxb/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.