Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating a global Js Object
// Create an object in the global scope, pass in window, jQuery, and the global object into the anonymous function.
window.myObject = ( function( window, $, myObject ) {
// Create our object, properties, and functions.
myObject = {
window: $( window ), // Remove if you don't need it, makes your object smaller.
// Access variables using myObject.options
options {
loadedText: 'myObject loaded.', // Loaded message for when you first add, remove once you know it's loading.
},
// First function loaded in this object.
__construct: function() {
console.log( myObject.options.loadedText ); // Remove once you know your object is loading.
// Bind things.
$( '.my-thing' ).on( 'click', myObject.myFunction ); // Don't have to pass event, jQuery does that.
},
myFunction( event ) {
// Do something.
}
};
$( myObject.__construct ); // Load the object's first function.
return myObject; // Return the object to window.myObject so it can all be accessed from the global scope.
} ) ( window, jQuery, window.myObject );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.