Is it possible to call function.apply without changing the context? Is it possible to call function.apply without changing the context? node.js node.js

Is it possible to call function.apply without changing the context?


If I understand you correctly:

                          changes context                   |    n     |      y       |accepts array    n |  func()  | func.call()  |of arguments     y | ???????? | func.apply() |

PHP has a function for this, call_user_func_array. Unfortunately, JavaScript is lacking in this regard. It looks like you simulate this behavior using eval().

Function.prototype.invoke = function(args) {    var i, code = 'this(';    for (i=0; i<args.length; i++) {        if (i) { code += ',' }        code += 'args[' + i + ']';    }    eval(code + ');');}

Yes, I know. Nobody likes eval(). It's slow and dangerous. However, in this situation you probably don't have to worry about cross-site scripting, at least, as all variables are contained within the function. Really, it's too bad that JavaScript doesn't have a native function for this, but I suppose that it's for situations like this that we have eval.

Proof that it works:

function showArgs() {    for (x in arguments) {console.log(arguments[x]);}}showArgs.invoke(['foo',/bar/g]);showArgs.invoke([window,[1,2,3]]);

Firefox console output:

--[12:31:05.778] "foo"[12:31:05.778] [object RegExp][12:31:05.778] [object Window][12:31:05.778] [object Array]


'this' is a reference to your function's context. That's really the point.

If you mean to call it in the context of a different object like this:

otherObj.otherFn(args)

then simply substitute that object in for the context:

otherObj.otherFn.apply(otherObj, args);

That should be it.


Simply put, just assign the this to what you want it to be, which is otherFn:

function fn() {    var args = Array.prototype.slice.call(arguments);    otherFn.apply(otherFn, args);}