简体   繁体   中英

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?

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.net/PNLxb/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM