Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should "parent" not be used as javascript variable name (reserved words)

Tags:

javascript

I've often used the word "parent" as a JavaScript variable name, and have never had any problems.

I've recently learned that "parent" can refer to something else such as when used to access an element in an IFrame's parent such as parent.document.getElementById("someID").

Should I stop using the word "parent" as a JavaScript variable name, and go through all my existing script to change it? Note that http://msdn.microsoft.com/en-us/library/ie/0779sbks%28v=vs.94%29.aspx and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words do not indicate that I shouldn't.

like image 435
user1032531 Avatar asked Oct 10 '13 13:10

user1032531


3 Answers

'parent' is not a reserved word but a global object in the browser's execution environment. Whether or not you want to have a variable name that conflicts with that is your decision.

For reference, here is a list of actual reserved words in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words

like image 90
staafl Avatar answered Sep 28 '22 16:09

staafl


If it makes sense for your variable to be called parent then go ahead and name it that, you just need to be aware that it will shadow the parent property of the window object (the global scope), but that's not an issue since you can explicitly reference that using window.parent rather than just parent wherever you need to work with it.

The only time it should become an issue is if there is code that shares scope with your parent variable which is attempting to access window.parent without explicitly specifying that they want the property, and that's probably an indication that the code needs to be tweaked.

like image 24
Anthony Grist Avatar answered Sep 28 '22 16:09

Anthony Grist


"JavaScript" isn't the same as "ecosystem within which JavaScript is executed".

Browsers have the window and document references, which have properties... like parent. You can still reference the global parent. If your parent is called on a different object there's no collision anyway.

like image 30
Dave Newton Avatar answered Sep 28 '22 15:09

Dave Newton