【问题标题】:What does declaring a function within an IIFE, assigned to var with the same name, mean? [duplicate]在 IIFE 中声明一个函数并分配给具有相同名称的 var 是什么意思? [复制]
【发布时间】:2020-07-13 06:00:52
【问题描述】:

当一个名为 Glitcher 的函数在 IIFE 中声明,其返回值分配给变量 Glitcher,即同名,这意味着什么?我不知道我应该如何理解。

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;
})();

【问题讨论】:

  • 不管里面叫什么,都是块作用域。
  • 这对于调试目的可能很重要,因为它将设置构造函数的 .name。一些网络控制台(例如 Chrome 的)将在记录实例对象时使用此函数的名称。

标签: javascript function iife


【解决方案1】:

如果某个变量被较小范围内的同名变量屏蔽,则您无法访问较宽范围内的变量。

这里没关系,因为全局变量在 IIFE 完成之前没有值,此时返回值被分配给它......并且返回值是同名变量的值在更窄的范围内。


这只是一种在使用 IIFE 限制全局变量创建的同时,始终调用持有构造函数 Glitcher 的变量的方法。

【讨论】:

    猜你喜欢
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2016-06-19
    • 2011-06-11
    • 2011-03-09
    • 2015-12-20
    相关资源
    最近更新 更多