DavidB DavidB - 1 year ago 68
Javascript Question

Javascript IIFE, don't understand how this variable becomes global

Take the following block of code. There is no return statement, and yet MyApp.VideoTracker is a property on the window object and so is accessible globally.

(function(window, $, VideoTracker, undefined) {
"use strict";

VideoTracker.loadAPI = function(apiReadyCallbackFn) {

VideoTracker.destroy = function(iframeElement) {

VideoTracker.trackVideos = function() {

$().ready(function() {
var youTubeIframes = $('iframe[src*="youtube.com"]');
if (youTubeIframes.length > 0) {

}(window, jQuery, MyApp.VideoTracker = MyApp.VideoTracker || {}));

Is this because of the way it is defined in the function call, i.e.:

MyApp.VideoTracker = MyApp.VideoTracker || {}

An explanation would be great, as I can see this must be the reason but don't understand why?

Answer Source

Yes, essentially you're calling the IIFE with what are global variables.

Assuming you've defined MyApp already - and before the function body is executed - you're calling it with an expression that either sets the VideoTracker property of MyApp with the existing MyApp.VideoTracker or an empty object literal, and that reference is being passed into your IIFE.

Hope that helps.