最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why "String.prototype={}" won't work? - Stack Overflow

programmeradmin5浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 10

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

you have to write like :

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

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

fiddle : http://jsfiddle/PNLxb/

发布评论

评论列表(0)

  1. 暂无评论