views:

238

answers:

3

Hi,

If I want to add an isEmpty method to all JavaScript arrays, I would use the following code

Array.prototype.isEmpty = function() {
  return this.length == 0;
}

Assume this code is in a file foo.js. If I want isEmpty to be available on all pages of a web site, would I need to include foo.js in all the HTML files? In other words, do the prototypes get "reset" whenever the user navigates to a different page?

Thanks, Don

A: 

yes, http is stateless so each page is loaded separately.

however adding to Array.prototype isn't a good idea. it means that if you try and loop round it you can get yourself into trouble.

Annan
Can you be a bit more specific about how I can get myself into trouble?
Don
@Don, It's only an issue for `for(elem in array)...`, the issue @Annan was referring to is that for..in enumeration of an object will include any properties you add to any objects on the prototype chain. That said you really shouldn't be using for-in enumeration on an array, it's really inefficient
olliej
I wasn't aware of performance overheads with using for(in) loops, it's good to know. I use them myself for arrays because it seems more logical and reads easier.
Annan
Are there benchmarks for for/in? As far as I know, it's not inefficient, just dangerous. That said, that's why hasOwnProperty or propertyIsEnumerable exist, and Array.prototype is only dangerous if you expect poor coding downwind.
eyelidlessness
I was hoping my original question wouldn't devolve into a discussion about monkey-patching. For what it's worth, Douglas Crockford (emperor supreme of JavaScript) encourages modifying built-in prototypes in his "The Good Parts" book
Don
+2  A: 

Yes, you will have to modify the prototype after each page loads

Yisroel
+3  A: 

Yes, you wil need to include your code on each page load.

Think of each page load as a compile/linking cycle. All the various bits of Javascript on the page are linked together1 and then executed as one giant program. The next time a page is loaded, the default Javascript objects start in a fresh state.


1. Linked together in a brain-dead "every piece of code shares the same global namespace" fashion

Alan Storm