将参数传递给 Javascript IIFE 构造函数

Passing arguments to a Javascript IIFE constructor

我正在努力了解 Javascript OO,使用 IIFE 模块模式来模仿 class:

var MyClass = (function() {
  // Constructor
  return function() {
    return {
      foo: 'foo'
    }
  }
}());

我正在传递类似这样的参数:

var MyClass = (function() {
  // Constructor
  return function(arg) {
    return {
      foo: function() {
        return 'foo'+arg
      }
    }
  }
}());

为了模仿 classical 继承,我使用了建议的模式 here:

function inherit(base, child, obj) {
  child.prototype = Object.create(base.prototype);
  child.prototype.constructor = child;
  obj&&Object.keys(obj).forEach(function(key){
    child.prototype[key] = obj[key];
  })
}

var Base = (function() {

  var init = function() {};

  init.prototype = {
    foo: function() {
      return "foo";
    }
  };

  return init;

}());

var Child = (function() {

  var init = function() {
    Base.call(this); 
  };

  inherit(Base, init, {
    bar: function() {
      return 'bar';
    }
  });

  return init;

}());

到目前为止一切顺利。我唯一的问题是在以上述方式进行继承时理解如何将参数传递给我的 class 构造函数。我喜欢这样的事实,在 'pure' IIFE 模块中,我可以简单地引用其中定义的任何函数中的构造函数参数,以便它们成为闭包。但是,当我使用构造函数变量添加这些后续函数时,如何访问构造函数参数,如上面的继承示例所示?我想我可以做类似的事情:

var init = function(arg) {
  this.theArg = arg;
};

然后我可以在后续的任何内容中访问它:

init.prototype = {
    foo: function() {
      return "foo"+this.theArg;
    }
  };

而对于 child:

var init = function(arg) {
    Base.call(this, arg); 
  };

这使得 arg 对外界可用,所以要使其 read-only 我想 getter 会起作用:

var init = function(arg) {
    var theArg = arg;
    this.getArg = function() { return theArg };
  };

从表面上看,我看不出有什么不对,而且我也想不出更好的选择。有吗?我是否遗漏了一些明显的东西?

I can't think of a better alternative. Is there one?

没有。不在你的例子中。

I like the fact that in the 'pure' IIFE module I can simply refer to the constructor parameter in any functions defined within it, so that they become closures.

您可以在每个函数中访问 args,因为在您的第一个示例中,您在每个对象实例上分别定义 foo。因此 foo 的每个定义都有一个单独的闭包,其中包含定义时传递的 args

这也是唯一可能的,因为 foo 是在包含您的 args.

的范围内定义的

But how do I access constructor params when I'm adding these subsequent functions ... in the inheritance example above?

通过使用您找到的经典继承模式,您现在可以在构造函数原型上定义 foo 函数。这意味着只有一个 foo 定义存在,它被使用您的构造函数创建的所有实例继承。所以 foo 不能再具体到每个实例了。

如您所想,这也意味着 foo 不再定义在包含 args 的范围内并且没有直接访问权限。

因此,您将 args 分配给 this.thisArgs 是正确的,这允许 foo 在每个实例上访问 thisArgs。您已将 foo 设为通用案例函数,可以处理它所应用的任何实例。

向 IIFE 构造函数传递参数: IIFE 本身不是构造函数,它只是构建构造函数对象。 IIFE 的作用域早已在构造函数本身被调用时返回。

Am I missing something obvious?

是的。 Javascript 是一种原型 语言。它从来没有像 "classical" 语言那样。让它成为 Javascript。 :)