Saving function area when using .apply (...) function

Consider the following example:

var funcToCall = function() {...}.bind(importantScope);

// some time later
var argsToUse = [...];
funcToCall.apply(someScope, argsToUse);

I want to save the 'importantScope' funcToCall. However, I need to use apply to apply an unknown number of arguments. "apply" requires me to provide "someScope". I don’t want to change the scope, I just want to apply the arguments to the function and save its scope. How should I do it?

+3
source share
1 answer

You can pass any old object (including null) as the first argument of the call apply()and thiswill remain importantScope.

function f() {
    alert(this.foo);
}

var g = f.bind( { foo: "bar"} );

g(); // Alerts "bar"
g.apply(null, []); // Alerts "bar"

bind , , this , , bind. , , this . ( , ECMAScript 5, Prototype , , ):

Function.prototype.bind = function(thisValue) {
    var f = this;
    return function() {
        return f.apply(thisValue, arguments);
    };
};
+7

Source: https://habr.com/ru/post/1762932/


All Articles