这就像我之前的问题一样,但这是关于函数而不是变量。我有一个模块,我想在其中模拟一个函数。这是我的咖啡脚本代码:
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()