0

这就像我之前的问题一样,但这是关于函数而不是变量。我有一个模块,我想在其中模拟一个函数。这是我的咖啡脚本代码:

root = exports ? this

root.prod = (->
  iWantToBeMocked = -> alert "production"
  doSomething = -> iWantToBeMocked()

  return {
    doSomething: doSomething
    iWantToBeMocked: iWantToBeMocked
  }
)()

root.test = (->
  root.prod.iWantToBeMocked = -> alert "I mocked this"
  root.prod.doSomething()

  return {}
)()

这会提醒“生产”,但我希望它提醒“我嘲笑这个”。我怎样才能做到这一点?

这是获取输出的javascript:

var root;

root = typeof exports !== "undefined" && exports !== null ? exports : this;

root.prod = (function() {
  var doSomething, iWantToBeMocked;
  iWantToBeMocked = function() {
    return alert("production");
  };
  doSomething = function() {
    return iWantToBeMocked();
  };
  return {
    doSomething: doSomething,
    iWantToBeMocked: iWantToBeMocked
  };
})();

root.test = (function() {
  root.prod.iWantToBeMocked = function() {
    return alert("I mocked this");
  };
  root.prod.doSomething();
  return {};
})();

更新

我已经想出了如何通过应用我原来的问题的答案来自己解决我的问题:

root = exports ? this

root.prod = (->
  iWantToBeMocked = -> alert "production"
  doSomething = -> this.iWantToBeMocked()

  return {
    doSomething: doSomething
    iWantToBeMocked: iWantToBeMocked
  }
)()

root.test = (->
  root.prod.iWantToBeMocked = -> alert "I mocked this"
  root.prod.doSomething()

  return {}
)()

注意this这一行中的:doSomething = -> this.iWantToBeMocked(). 但是这里还有一个问题需要回答。我不明白为什么我必须在this这里使用。我希望有人向我解释嘲笑 doSomething = -> this.iWantToBeMocked()之间的区别。doSomething = -> iWantToBeMocked()

4

1 回答 1

1

在您的prod对象中,您有2 个名为 的对象iWantToBeMocked。第一个是包含原始警报的函数的变量;第二个包含在返回的对象中。

内部是一个私有变量var iWantToBeMocked root.prod设置 时root.prod.iWantToBeMocked,您正在更改返回的函数,但不会触及私有成员。

现在,当你使用

doSomething = -> this.iWantToBeMocked()

doSomething将寻找一个附加到this恰好是的上下文的方法root.prod,因此它不会调用私有 ,而是调用.iWantToBeMockedroot.prod.iWantToBeMocked

于 2013-07-02T18:56:06.303 回答