0

I'm trying to offload common functions to a separate functions.js file in order to clean things up. I've managed success in making the global functions work, but there's some inconsistency in the way that I need to write and call the function that is confusing me.

One of my global functions:

$.getTld = function() {
    var tld = document.location.hostname.split('.').pop();
    return tld;
};

I can call it like this from another JS file:

$.setPersonaCookie = function(name, value, days) {
    $.cookie(name, value, {
        expires: days, // Expires in 360 days
        path: '/', // Is on the default path
        domain: 'mydomain.' + $.getTld(), // The value of the domain attribute of the cookie
        secure: $.getProtocol() // set secure cookies - setting in htaccess
    });
    return;
};

In my same functions.js file I've set up another function in the same way as I did with the $.getTld function:

$.getQueryVariable = function(name, url) {
    if (!url) url = location.href;
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    return results == null ? null : results[1];
};

And I'm calling the function like this:

$(document).getQueryVariable('q');

But, I get a console error indicating that $.getQueryVariable is not defined. In order to make it work, I have written the function like this instead:

$.fn.getQueryVariable = function(name, url) {...};

When written this way, I can successfully call the function.

So, why do I need to add the extra .fn to the getQueryVariable function to make this work as a global function?

Vaughn D. Taylor
  • 617
  • 1
  • 8
  • 20
  • 1
    `$.fn` = `$.function`, `$` is global, so making it a `global.function` makes it global .. https://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean – treyBake Jun 15 '18 at 15:41
  • 1
    Aside from that it's not a great idea to pollute the `$` namespace with custom logic. If you really have to have global functions create your own namespace and put them in that. – Rory McCrossan Jun 15 '18 at 15:43
  • 1
    ^^^ I strongly agree with that statement. It can be confusing for other programmers if they see `$(...).bingo()` and that leads them to believe it is a jQuery (plugin) method. – Taplar Jun 15 '18 at 15:44
  • `window.myApplication = {};` is enough to create a global variable from any where, and then different files can add their functionality to that variable. – Taplar Jun 15 '18 at 15:47
  • I appreciate the comments and I want to make sure I'm doing this the right way. @RoryMcCrossan, do you think you could show me and example on how to create a namespace? I use these functions throughout, and I'm trying to keep things as clean and sensible as possible. – Vaughn D. Taylor Jun 15 '18 at 16:03
  • Here you go: https://stackoverflow.com/a/5947280/519413 – Rory McCrossan Jun 15 '18 at 16:04

0 Answers0