15.1.7.7.1.2 Comparing Namespace to PL/SQL Package
Use an immediately invoked function expression (IIFE) to create an app namespace for reusable JavaScript helper functions.
JavaScript doesn't have packages like PL/SQL, so developers use the pattern in
app.js to simulate a modular structure. The high-level pattern
looks like
this:// Define an "app" namespace with exported functions
const app = (function($) {
// --- Private Functions ---
function myPrivateFunction(itemName) {…}
// --- Public Functions (returned below!) ---
function setDialogTitle(title) {…}
function areDifferent(x, y) {…}
return {
setDialogTitle,
areDifferent
};
})(apex.jQuery);Known as an immediately invoked function expression (IIFE) the pattern breaks down as follows:
- The function
(function($) {…})(apex.jQuery);is defined and then immediately called. - Its single parameter named
$is passed the correct version of jQuery APEX uses. - It returns any functions to expose publicly as properties of an object.
- The
{setDialogTitle, areDifferent}in thereturnstatement is legal shorthand for:{ setDialogTitle: setDialogTitle, areDifferent: areDifferent } - That object becomes the value of the
appvariable.
So when you later write the following line of code in an APEX page, it calls the setDialogTitle function inside the app function library.
app.setDialogTitle("Hello");Since app defines a unique name to unambiguously qualify its exported function names, JavaScript developers call it a namespace.
By attaching your helper functions to a single namespace object (
app), you:
- Keep your global "footprint" of additional top-level names small.
- Group related logic in one place.
- Make your code easier to organize and maintain.
- Define a public specification of exported functions.
- Maintain your ability to change private functions in the namespace body.
This is very similar to how you use packages in PL/SQL.
Caution:
Unlike PL/SQL, JavaScript does not support defining multiple versions of the same function name with different parameter lists. If you inadvertently do this, the function defined last in the file "wins". To achieve a similar effect, define your function with all possible parameters, then test whether a particular parameter was not supplied by checking an expression like the following:
if (typeof yourParam === "undefined") {
// yourParam was not passed
}Parent topic: Adding Static Application JavaScript File