Home > Article > Web Front-end > Is Underscore Prefix in JavaScript Just a Convention or More?
Underscore Prefix in JavaScript: Convention or More?
Unlike Python's private class methods, the underscore prefix in JavaScript is merely a convention that serves as an indication of non-public elements. This convention is widely adopted to distinguish private variables and functions from public ones.
In JavaScript, private instance variables are not enforced by the language itself. However, using an underscore prefix helps to establish a consistent naming convention that allows developers to identify and avoid modifying internal implementation details.
This convention is particularly useful in JavaScript, where encapsulation is not directly supported. By using an underscore prefix, developers can communicate the intended privacy of variables and methods, even though the code can still be accessed and modified by other parts of the program.
Take the following JavaScript code as an example:
function AltTabPopup() { this._init(); } AltTabPopup.prototype = { _init : function() { ... } }
The _init method, signified by its underscore prefix, is intended to be a private method, although there is no technical restriction preventing it from being accessed and modified.
Similarly, the use of underscore prefixed variables, such as _currentApp and _motionTimeoutId, is a convention that indicates their internal nature.
While the underscore prefix in JavaScript does not provide any inherent protection or enforcement, it plays a valuable role in establishing clear boundaries and documenting the intent to keep certain elements private.
The above is the detailed content of Is Underscore Prefix in JavaScript Just a Convention or More?. For more information, please follow other related articles on the PHP Chinese website!