我正在尝试创建一个模拟助手,它可以模拟一个类并返回特定方法名称的特定值:
methods_values =
a : 1
b : 2
c : 3
methods = {}
for method, value of methods_values
methods[method] = ->
value
console.log methods
// Outputs "{ a: [Function], b: [Function], c: [Function] }"
class MockClass
methods
mock_instance = new MockClass()
console.log mock_instance
// Outputs "{}"
for method, value of methods_values
console.log method
// Outputs "a"
console.log mock_instance[method]()
// Gives error "TypeError: Object #<MockClass> has no method 'a'"
我可以从编译的代码中看出为什么这不起作用,但是我无法确定前进的道路。这是否可能通过coffeescript实现,或者编译方式是否会阻止我获得正确的范围?
解决方案:由于@Leonid的回答,下面的代码可以工作:
methods_values =
a : 1
b : 2
c : 3
mock_methods = (proto, _methods_values) ->
for method, value of _methods_values
do (_value = value) ->
proto[method] = -> _value
return
class MockClass
mock_methods @::, methods_values
mock_instance = new MockClass()
for method, value of methods_values
console.log method
console.log mock_instance[method]()
产出:
a
1
b
2
c
3
发布于 2014-12-07 11:10:36
要做到这一点,您应该将所有的methods
混合到MockClass.prototype
中。下面是一个这样做的例子:
mixin = (proto, methods) ->
for name, fn of methods
proto[name] = fn
return
class MockClass
mixin @::, methods
或者在你的情况下
mock_methods = (proto, methods_values) ->
for method, value of methods_values
do (value) -> proto[method] = -> value
return
class MockClass
mock_methods @::, methods_values
https://stackoverflow.com/questions/27340907
复制相似问题