0

What does it mean when a function called Glitcher is declared inside of an IIFE whose return value is assigned to the variable Glitcher, i.e. the same name? I don’t know how I should understand this.

var Glitcher = (function() {
  function Glitcher(options) {
    this.canvas = document.createElement('canvas');
    this.context = this.canvas.getContext('2d');
    this.origCanvas = document.createElement('canvas');
    this.origContext = this.origCanvas.getContext('2d');
    this.options = options;
  }

  Glitcher.prototype.glitch = function(url, callback) {
    var _this = this;

    this.loadImage(url, function(img) {
      _this.renderImage(img);
      _this.process();
      callback();
    });
  };

  // deleted some code.....

  return Glitcher;
})();
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Biojk83
  • 11
  • 2
  • 1
    does not matter what it is named inside, it is a block scope. – epascarello Apr 01 '20 at 13:14
  • It may matter for debugging purposes since it will set the .name of the constructor. Some web-consoles, (e.g Chrome's) will use this function's name when logging an instance object. – Kaiido Aug 21 '20 at 09:00

1 Answers1

0

You can't access a variable in a wider scope if it is masked by a variable of the same name in a narrower scope.

That doesn't matter here because the global variable doesn't have a value until the IIFE is complete, at which point the return value is assigned to it … and the return value is the value of the variable with the same name in the narrower scope.


This is just a way of consistently calling variables holding the constructor function Glitcher while using the IIFE to limit the creation of global variables.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335