我将函数调用存储在变量中。

var snippet = function { alert('a') };
snippet.call(); // Displays an alert


我的问题是我需要将变量作为函数的参数传递。

var snippet;
function() {
   var word1 = 'hello';
   var word2 = ' world';
   snippet = function() { alert( word1 + word2 ); };
}


当我调用“代码段”时,变量未定义:

snippet.call(); // Cannot read property 'x' of undefined


如何保存函数,以便将word1word2的值保存为参数而不是实际变量? (因此,无论是否定义了var,我以后都可以调用它)

最佳答案

这应该可以解决问题:

var snippet = function ( word1, word2 ) {
  alert ( word1 + word2 );
};

snippet ( "foo", "bar" );
// or
snippet.call ( ctx, "foo", "bar" ); // where `ctx` is the context you wish to use


call()函数的更多信息:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call

关于javascript - 将变量的值传递给函数参数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13966795/

10-12 00:06