Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why some attribute names start with double underscore in JavaScript?

I see some attributes of some objects in JavaScript start with double underscore. For example, something like __defineGetter__ or __defineSetter__ or __proto__. Is it a convention defined ECMAScript specification? Or maybe it's just a convention in the developer community?

like image 313
Saeed Neamati Avatar asked Jul 01 '11 11:07

Saeed Neamati


People also ask

What does double underscore mean in JavaScript?

Double underscore (__) in front of a variable is a convention. It is used for global variable (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define private variable.

Can JavaScript variables start with underscore?

Variable names are pretty flexible as long as you follow a few rules: Start them with a letter, underscore _, or dollar sign $. After the first letter, you can use numbers, as well as letters, underscores, or dollar signs. Don't use any of JavaScript's reserved keywords.

What does underscore in front of variable mean JavaScript?

Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

What does a double underscore in front of a property of an object mean?

Double underscores are used for fully private variables. According to Python documentation − If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores.


1 Answers

These are properties defined by the specific browser and are not defined by ECMAScript.

Therefore, name collision needs to be avoided. If they called the property defineGetter, then there would be no guarantee that the website's code didn't already define a property by that same name -- and that would cause many problems. However, appending two underscores has become the defacto way to define browser specific properties (since it's much less likely some website will use that convention).

You may notice that other browsers start using the same naming convention as others (like using __proto__), but that's still not universally guaranteed between all browsers (eg, IE does not define the __proto__ property).

Also: the convention of using two underscores for "system-defined" identifiers (as opposed to programmer-defined identifiers) harkens back a long time, so I don't know when that convention "started" -- At least as long as C++ (see http://en.wikipedia.org/wiki/Name_mangling#Simple_example )

like image 189
Alexander Bird Avatar answered Oct 09 '22 06:10

Alexander Bird