Javascript 窗口、文档、数学、未定义在类实例化中作为参数传递

Javascript 窗口、文档、数学、未定义在类实例化中作为参数传递,javascript,class,oop,Javascript,Class,Oop,在创建js类的过程中,我看到window、document、Math和undefined在Begging和类的末尾作为参数传递。 它们有用吗?它们是什么意思 var MyClass = (function (window, document, Math, undefined) { function MyClass (opts) { this.init(opts); } MyClass.prototype = { init: function (opts) {

在创建js类的过程中,我看到window、document、Math和undefined在Begging和类的末尾作为参数传递。 它们有用吗?它们是什么意思

var MyClass = (function (window, document, Math, undefined) {

  function MyClass (opts) {
    this.init(opts);
  }

  MyClass.prototype = {

    init: function (opts) {

    }

  return MyClass;
})(window, document, Math, undefined);

您缺少一个结束括号

var MyClass = (function (window, document, Math, undefined) {

    function MyClass (opts) {
        this.init(opts);
    };

    MyClass.prototype = {

        init: function (opts) {

        }
    }; /* <-- closing brace here */

    return MyClass;

})(window, document, Math);
因此,任何依赖于数学的代码都会突然崩溃


除上述原因外,局部变量可以被缩小。因此,减少了最终通过有线传输的脚本的大小。

使用:

var MyClass = (function (window, document, Math, undefined) {
 ...
})(window, document, Math, undefined);
他被误导了。如果目的是获得对本机方法的“安全”访问,那么如果在代码运行之前已经为这些标识符分配了新值,那么它将失败

您所能做的就是:

var myClass = function(global) {

  // In here you can be certain that global references the global (window) object
  var window = global; 

  // and that the value of undefined will be undefined
  var undefined;

  // But you are still uncertain of
  var document = window.document;
  var Math = window.Math;

  ...

// guaranteed access to the global object
}(this));
它的值在任何上下文中都不能被覆盖(尽管可以通过调用或绑定在输入函数时设置),因此在全局执行上下文中它必须引用原始全局对象。但是,数学和窗口属性可能已经被重新分配,您无法停止(尽管未来版本的ECMAScript可能会在某些情况下使其不可能)

因此,如果IIFE必须在重新分配感兴趣的属性之前运行,那么创建别名没有任何价值。尽管正如其他人所说,这可能有助于缩小规模

请注意,创建宿主对象和方法的别名是有问题的,例如

var getEl = document.getElementById;
var el = getEl('foo');

可能会引发错误,因为getElementById函数可能会作为文档方法调用,因此其设置可能不正确。

这看起来毫无意义,因为所有这些都是全局可用的。您能否共享指向原始代码的链接?我很惊讶在结尾看到
未定义的
。我认为你是对的,但当然这是毫无意义的,除非能保证此代码将在执行重新分配的任何其他代码之前运行。;-)它不必在任何其他脚本之前运行,javascript是事件。任何在事件发生后更改全局对象的脚本都将更改行为,从而向前…但是,在脚本运行之前,全局对象可能已更改,而此脚本需要标准对象。@Qantas949这是缓解而不是预防。你不能完全阻止人们自吹自擂……那么,首先为什么要这么做(除了缩小,这是这样做的正当理由)?
var getEl = document.getElementById;
var el = getEl('foo');