Javascript 如何在不更改上下文的情况下将参数数组传递给函数?

Javascript 如何在不更改上下文的情况下将参数数组传递给函数?,javascript,Javascript,我处理的是每个函数都绑定到特定上下文的函数。在代码的其他地方,我必须使用数量可变的参数调用它们。通常,我会使用apply,但这会改变上下文(this) 我是否可以在不更改函数中此的现有绑定值的情况下实现应用(null,args)的效果 (当需要调用时,我手头没有变量中函数的this值。) 顺便说一句,这里的问题并不是重复的,尽管标题很有前途,OP只是试图在方法调用中添加语法糖。令人惊讶的是,事实证明这不是一个问题。如果函数绑定到上下文,则可以使用apply安全地调用它,而无需更改上下文 appl

我处理的是每个函数都绑定到特定上下文的函数。在代码的其他地方,我必须使用数量可变的参数调用它们。通常,我会使用
apply
,但这会改变上下文(
this

我是否可以在不更改函数中此的现有绑定值的情况下实现应用(null,args)的效果

(当需要调用时,我手头没有变量中函数的
this
值。)


顺便说一句,这里的问题并不是重复的,尽管标题很有前途,OP只是试图在方法调用中添加语法糖。

令人惊讶的是,事实证明这不是一个问题。如果函数绑定到上下文,则可以使用
apply
安全地调用它,而无需更改上下文

apply
的第一个参数可以设置为任何-
undefined
null
窗口
,另一个对象。如果函数被绑定,则没有任何效果

例如:

var o = { id: "foo" },
    args = [ "bar", "baz" ],
    f = function () {
      var args = Array.prototype.slice.call( arguments ).join( ", ");
      return "Called in the context of " + this.id + " with args " + args; 
    },

    // Binding f to o with ES5 bind
    boundNative = f.bind( o ),

    // Binding f to o with a closure
    boundWithClosure = ( function ( context ) { 
        return function () { 
            return f.apply( context, arguments ); 
        } 
    } )( o );

// Does boundNative.apply( whatever, args ) change the context?
console.log( boundNative.apply( undefined, args ) );
console.log( boundNative.apply( null, args ) );
console.log( boundNative.apply( window, args ) );
console.log( boundNative.apply( { id: "quux" }, args ) );

// Same test with the closure
console.log( boundWithClosure.apply( undefined, args ) );
console.log( boundWithClosure.apply( null, args ) );
console.log( boundWithClosure.apply( window, args ) );
console.log( boundWithClosure.apply( { id: "quux" }, args ) );
所有调用都返回“在带有args bar、baz的foo上下文中调用”,因此没有问题

我不得不承认一开始这个结果让我很惊讶。毕竟,
apply
强制执行一个上下文-为什么会被忽略?但事实上,这很有道理

是的,原始函数(
f
)引用了
this
,用
apply
调用它会改变它的值。但我们并不是在调用原始函数


绑定函数是一个完全独立的实体,它不再引用此。对于ES5
bind
,这一点不太明显,但是闭包构造给出了它。
this
关键字不会出现在IIFE返回的函数中的任何位置。调用它,没有任何东西可以改变。

上下文总是存在的,它可以是全局对象(窗口)或某个特定对象的上下文。调用函数时,它使用一些上下文。而且你肯定可以访问它。函数存在于可见范围内(上下文和范围不相同)


你能提供一些示例代码吗?举个例子就好了。我想不出调用
some.method.apply(null,args)
的地方,如果问题的根源不在代码的体系结构中,就无法执行
some.method.apply(some,args)
。如果不调用函数,则
this
必须在函数中进行窗口引用,我不确定您在这个内部函数中是否有不同的ref,即使您可以通过
apply(window,args)
methodUse
apply(this,args)
。您说变量中没有
this
,但肯定在
this
中必须有
this
,是吗?
var text = "Current context is ";

function A() {
    this.test = "A";
    this.print = function(msg) {
        return msg + this.test;
    }
};

function B() {
    this.test = "B";
}

var testObj = {
    test: "testObj"
};

test = "window";

var msgFn = function (msg) {
    return msg + "msgFn";
}

var a = new A();
var b = new B();

a.print.apply(a, [text]); // Current context is A
a.print.apply(b, [text]); // Current context is B
a.print.apply(null, [text]); // Current context is window
a.print.apply(testObj, [text]); // Current context is testObj
msgFn.apply(msgFn, [text]); // // Current context is msgFn