Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top