How to create a well-formed global javascript object containing special functions

I am creating a small project that is highly dependent on JavaScript. I came from php / mysql and now go to node.js / javascript / mongodb and I want to say that this is a pretty reasonable switch.

I want to create a simple object that has a special function that I can use on the page. I look at some tutorials and look at libraries like jquery and the spine, but I need to get the final advice on my decision.

I only need small features and cross-browser support, so I do not choose something like a trunk. Maybe this will be a bad transition to this later, when I will be better versed in JavaScript programming.

What bothers me is whether to use new , or perhaps wrap the code in a self-starting function.

I see that jquery creates an object inside a window and then exposes this, but I have no idea how this works.

Enough intro, now to the point. I created something like this:

 var $s = Object.create({ page: Object.create({ title: 'pagetitle', html: '', data: {}, render: function(){ // Basic render function } }), socket: Object.create({ // My websocket connection }), store: function(key, value) { localStorage.setItem(key, JSON.stringify(value)); }, retrieve: function(key) { var value = localStorage.getItem(key); return value && JSON.parse(value); }, slugify: function(slug){ return slug.replace(/[^a-zA-Z 0-9-]+/g,'').toLowerCase().replace(/ /g,'-'); } }); 

These are just a few random functions that I inserted.

I have not tested this yet, this is a project, I want to know if this is good.

Now I thought I could do something like this:

 $s.page.html = 'somehtml'; $s.page.render(); // Maybe $s.store( $s.page.title, $s.page.html ); 

I use jQuery and jQuery templates, so something like this is possible:

 $.tmpl( $s.page.html, $s.page.data ).appendTo( "#content" ); 
+4
source share
1 answer

Nothing special is needed here. You can create a global javascript object using a method like this:

 var myGlobalObject = {}; myGlobalObject.testFunction = function() { // put your code here }; 

Then you can call it like this:

 myGlobalObject.testFunction(); 

One of the slightly more flexible design patterns you'll often see is used as follows:

 var myGlobalObject = myGlobalObject || {}; myGlobalObject.testFunction = function() { // put your code here }; 

This is used when there can be many different pieces of code contributing to myGlobalObject , and they all want to make sure they are correctly declared before adding properties to it. This way of doing this, creates it, if it does not already exist, and if it already exists, leaves existing methods and properties on it. This allows each of several modules to contribute to myGlobalObject without regard to the order they load.

+6
source

Source: https://habr.com/ru/post/1401985/


All Articles