使用 apply() 与 call(),在这种情况下使用哪一个

Using apply() vs call(), which one to use in this case?

本文关键字:这种情况下 哪一个 call apply 使用      更新时间:2023-09-26

看看 Leaflet API 中的代码

我的问题是为什么wrapperFn.apply(context, args);</code> and <code>fn.apply(context, args);使用apply()而不是call().

你怎么知道使用哪一个?

感到困惑,因为我事先不知道我的传递函数是否使用数组。

limitExecByInterval: function (fn, time, context) {
    var lock, execOnUnlock;
    return function wrapperFn() {
        var args = arguments;
        if (lock) {
            execOnUnlock = true;
            return;
        }
        lock = true;
        setTimeout(function () {
            lock = false;
            if (execOnUnlock) {
                wrapperFn.apply(context, args);
                execOnUnlock = false;
            }
        }, time);
        fn.apply(context, args);
    };
},

Apply 接受单个参数数组,对于方法链接很有用,相当于在 Java 等中调用 super.

function makeNoise() {
   Foo.prototype.makeNoise.apply(this, arguments);
}

调用需要参数列表,更有用的其他情况,其中参数仅作为单个变量可用。

fn.call(this, x, y, z);

这只是简写

fn.apply(this, [x, y, z])

给定您需要使用 apply() 的参数数组