Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are functions scoped/namespaced within a <script> tag?

I'm working with a new application at work that we're building out using Knockout.js and jQuery. I prefer to "use strict" in my scripts, but since some of the libraries we're using don't work with "use strict" then I have to use the functional form.

I don't like placing javascript inside <script> tags inline, so I generally place everything in a separate file so it can be minified and gzipped by a pre-processor.

Given these criteria, I'm wondering how functions are scoped by default when you create them within a script tag. Right now I'm just doing something like this:

$((function(win) {
    "use strict";

    win.myFunction = function () {
        // do stuff
    };
}(window)));

As you can see I'm placing functions on my window object so I can call them in my view. I've noticed that I can call them in my jQuery templates without qualifying them (i.e.: I can just call myFunction instead if window.myFunction), but I'm concerned that this will not work across browsers. Do all browsers allow you to call functions placed in the window object without the fully-qualified name? How could I place a function in the global scope from within my anonymous method as I've defined above?

Thanks for the insight!

like image 751
Scott Anderson Avatar asked May 20 '11 21:05

Scott Anderson


1 Answers

The window object essentially is the global scope. Any variable that isn't scoped to a function is a property of the window object.

You can set a global variable by setting it as a property of the window object, as you just about do:

window.myFunction = function() {
    // do stuff
}

However, it's probably not a good idea to litter your global namespace with names. That way chaos, unmaintainable code and bizarre bugs come in. All jQuery functions, for example, are properties or sub-properties of the jQuery (or $) object. This means that they can define jQuery.each and not have to worry about collisions with a global each method. You should consider doing the same with your own code: create a single global namespacing object to house all your "global" methods.

like image 91
lonesomeday Avatar answered Oct 16 '22 07:10

lonesomeday