【问题标题】:Why is (this) & obj used after function? [duplicate]为什么 (this) & obj 在函数之后使用? [复制]
【发布时间】:2016-08-04 10:47:16
【问题描述】:
     (function(obj){
        $.each(Templates.inputs, function(key, value){
            obj.elementsKey.push(key);
            obj.elementsValueType.push(value.type);
        });
     }(this));

为什么this(this))在函数之后使用? 而obj作为参数的作用是什么

【问题讨论】:

  • this-上下文被传递给 IIFE。两个原因:1. each() 内的this 指的是集合中的当前元素2. 更少的 scope-chaingin 遍历。

标签: javascript jquery jquery-plugins


【解决方案1】:

这就是所谓的 IIFE - 您声明一个函数并立即调用它。 该函数有参数obj,其中放置了当前变量this。因此,例如,如果您在全局范围内运行此 IIFE,您将在函数内部的 obj 变量中获得 window 对象。

More about IIFE

【讨论】:

    猜你喜欢
    • 2012-04-27
    • 2020-04-07
    • 2013-09-09
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2014-11-07
    • 2019-09-11
    • 2017-07-08
    相关资源
    最近更新 更多