匿名函数似乎覆盖另一个?

时间:2014-07-29 20:51:21

标签: javascript anonymous-function

使用此代码:

function printStuff(thing1, thing2) {
  console.log(thing1 + ', ' + thing2); 
};

function callWith() {
  theFunc = arguments[0];
  theArgs = [].slice.call(arguments, 1);
  return function() {
    theFunc.apply(this, theArgs);
  };
};

x = callWith(printStuff, "apples", "cheese");
y = callWith(printStuff, "monkeys", "bananas");
x();
y();

...为什么x和y似乎保持相同的功能?如何获得所需的行为(即,存储两个不同的函数,这些函数总是使用创建时给出的参数运行printStuff)?

1 个答案:

答案 0 :(得分:0)

你需要像这样创建一个与printStuff方法不同的NEW瞬间 -

function printStuff(thing1, thing2) {
  console.log(thing1 + ', ' + thing2); 
};

function callWith() {
  theFunc = arguments[0];
  theArgs = [].slice.call(arguments, 1);
  return new function() { // RETURN A NEW INSTANCE SO THAT IT HAS ITS OWN ARGUMENTS
    theFunc.apply(this, theArgs);
  };
};

x = callWith(printStuff, "apples", "cheese");
y = callWith(printStuff, "monkeys", "bananas");
x();
y();