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.