-1

I'm trying to use a Javascript "prototype" like the one shown here: https://stackoverflow.com/a/17306971/606539

As a test, I have the following code in a "Bookmarklet" on Firefox.

javascript:(function(){Array.prototype.clear=function(){while(this.length>0){this.pop();}}var yy=[1,2,3];alert('yy=:"'+yy+'"');yy.clear();alert('yy=:"'+yy+'"');})()

Formatted for easier reading, it looks like this:

javascript:
(function(){
  Array.prototype.clear=function(){
    while(this.length>0){
      this.pop();
    }
  }
  var yy=[1,2,3];
  alert('yy=:"'+yy+'"');
  yy.clear();
  alert('yy=:"'+yy+'"');
}
)()

When I put this code in a bookmark and then click it, I get "nothing". I don't even see the first "alert". It would seem there is some error in the code. Usually, this would be a missing "closing quote mark", or a missing ";" or "}", or a misspelling, or other typo.

I have checked the code and I don't see anything wrong.

If I re-write the code to remove the "prototype", it works fine:

javascript:
(function(){
  function aryclear(A){
    while(A.length>0){
      A.pop();
    }
  }
  var yy=[1,2,3];
  alert('yy=:"'+yy+'"');
  aryclear(yy);
  alert('yy=:"'+yy+'"');
}
)()

Is there anything wrong that I'm missing? Do I need to load some library for this to work?


Edit:

The explanation in the answer by @msarchet was nearly correct and the code correction was exactly correct. It was a big help because it pointed out the missing semi-colon and gave me something to search for. Previous searches didn't reveal anything useful.

As it turns out this issue is described in an answer here: Do we need a semicolon after function declaration. A semi-colon is required after the closing } when declaring a prototype function or a function statement.

Community
  • 1
  • 1
Kevin Fegan
  • 1,292
  • 1
  • 16
  • 29

1 Answers1

2

In your single line you need to terminate after the prototypes closing } with a semi-colon

(function(){ Array.prototype.clear=function(){ while(this.length>0){ this.pop(); } }; var yy=[1,2,3];alert('yy=:"'+yy+'"');yy.clear();alert('yy=:"'+yy+'"');})()
msarchet
  • 15,104
  • 2
  • 43
  • 66
  • This works if I add a semi-colon following the "prototype's" closing `}` as you have shown in your answer. Can you please explain how this relates to the "while loop" since it's terminating the prototype, not the while loop. Also, in my alternate code that uses a function instead of a prototype, this works without the semi-colon even though the construction is identical. You are obviously correct (thank you), I'm just trying to understand why it works that way. – Kevin Fegan Sep 15 '15 at 00:44
  • Also, in the prototype, if I remove the `while` loop entirely and replace it with `this.length=0;` (as suggested by @epascarello), I still need to add the semi-colon following the `}` that closes the prototype. – Kevin Fegan Sep 15 '15 at 00:55
  • I did mean after the function declaration for the prototype. – msarchet Sep 15 '15 at 21:54