#78 ✓invalid

Variable name conflict with Template and $$

Reported by solrac | May 6th, 2008 @ 12:20 PM

Creating a global function or variable named "Template" in the same page that loads prototype.js will cause an error when trying to use the $$ utility function.

The error is not very apparent. Simply using $$ like so: $$('div')

would return a proper collection and not reveal the error.

However, with:

<div class="bob"></div>

attempting this: $$('div.bob') would return null, instead of the appropriate collection

The error is still not apparent. The error manifests when you try to assign the would-be collection to a variable, such as:

var myDivs = $$('div.bob');

At this point you would see the error:

(new Template(x[i])).evaluate is not a function

-- prototype, line 2771

The cause of this error must be at line 552:

var Template = Class.create({....

I suppose this is creating a global variable (object) named Template. Shouldn't everything be encapsulated in the Prototype namespace? This kind of problem should not be floating around waiting to murder developers who one day decide to create a single global variable named "Template" in their code.



Comments and changes to this ticket

  • Tobie Langel

    Tobie Langel May 6th, 2008 @ 12:15 PM

    • State changed from “new” to “invalid”

    Many people use the Template class directly, so removing it from the global scope isn't desired.

    The best solution, if you're developing a JS-heavy application and want to avoid such issues, is to create a namespace for your own code.

  • solrac

    solrac May 6th, 2008 @ 11:24 PM

    Sounds good, until you decide to name the namespace for your code "Template"


    Perhaps prototype should issue a document of reserved words required by Prototype in the global scope?

  • Juriy Zaytsev

    Juriy Zaytsev May 6th, 2008 @ 11:49 PM

    Good idea. Here they are:

    "Element", "Position", "$continue", "Insertion", "Toggle", "$F", "Field", "Form", "$$", "Selector", "$", "Ajax", "$R", "ObjectRange", "Hash", "$H", "$w", "$A", "Enumerable", "$break", "Template", "PeriodicalExecuter", "Try", "Abstract", "Class", "Prototype"

    (result of running: Object.keys(window).grep(/^(\$|[A-Z])/))

  • solrac

    solrac May 6th, 2008 @ 11:56 PM

    Cool, thanks. Nice grep. This should be up at the most viewed pages on the Prototype API web site.

    Some of these words will conflict with other JS libraries as well.

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

The Prototype JavaScript library.

Shared Ticket Bins

People watching this ticket