I'll admit I'm pretty green when it comes to JavaScript and it doesn't help that every time I think I'm getting it some weird curve ball throws me right off.

I've got a js file something like this:

(function (myiife, $) {

    var myArrayOfThings = [];    

    myiife.myFunction = function (id) {
        var cachedThing = myiife.getFromArray(id);
        if (cachedThing === null) {
            // get from server
        } else {
            // do something with cached item
        }
    };

    myiife.getFromArray = function (idToFind) {
        for (var i = 0, len = myArrayOfThings; i < len; i++) {
            if (myArrayOfThings[i].Id=== idToFind) {
                return myArrayOfThings[i]; // Return as soon as the object is found
            }
        }
        return null;
    };

}(window.myiife= window.myiife|| {}, jQuery));

What really confuses me is the proper way to expect to be able to call things. I guess I really don't understand the scope of things yet and I'm struggling to be honest.

Is it expected that if I want to call myFunction from the page it would HAVE to look like this?

onclick="myiife.myFunction(1)"

I've read stuff on scope but I'm obviously still missing something very fundamental in my understanding of it all.

From the examples I've seen I don't see others that seem to have to prefix function names with the iife name in order to execute things from the page.

Any good recommended reading would be appreciated as well.

有帮助吗?

解决方案

The global scope in Javascript (in a browser at least) is window. So what you've done is you've attached myiife to window and myiffe has a function called myFunction. So if you want to call it from the global scope (i.e. window) then, of course, you need to specify myiffe.myFunction().

What you may have seen other people do is something like this:

var myFunction = (function() {
    var counter = 0;
    return function() {
        counter++;
        console.log(counter);
    };
})()

Where they have an IIFE return something (in this case a function, in many other case people will return an object). In this case, since myFunction is a global variable, they can call it with just myFunction(). What they have achieved with the IIFE is to basically make the counter variable private. Only things inside the IIFE have access to it.

Of course, if you don't define myFunction inside of an IIFE, then it will just be a function in the global scope and can be called directly from the global scope.

 function myFunction() {
     // do something
 }

 myFunction();

But to your question on using this in an event handler - better practice would be to not inline your event handler in your HTML in the first place and instead bind it in code. This gives you more flexibility, cleaner separation and more maintainable code.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top