如何使用 CoffeeScript 模拟现有代码?
我想模拟 MarkdownDeep,我有以下 JavaScript 代码,
MarkdownDeep = new (function () {
this.Markdown = function () {
this.Transform = function (a) {
return "html";
};
};
})();
但在 CoffeeScript 中实现此代码时遇到问题
我尝试了以下操作
MarkdownDeep = new (->
@Markdown = ->
@Transform = (a) ->
"html"
)()
window.MarkdownDeep = MarkdownDeep
,但它不起作用,特别是在我的单元测试中 markdown = new MarkdownDeep .Markdown()
给出“未定义不是函数”,尽管 JS 版本模拟得很好。
I'd like mock out MarkdownDeep, I've the following code, in JavaScript
MarkdownDeep = new (function () {
this.Markdown = function () {
this.Transform = function (a) {
return "html";
};
};
})();
but I'm having trouble implementing this in CoffeeScript
I tried the following
MarkdownDeep = new (->
@Markdown = ->
@Transform = (a) ->
"html"
)()
window.MarkdownDeep = MarkdownDeep
but it doesn't work, specifically in my unit test markdown = new MarkdownDeep.Markdown()
gives "undefined is not a function", though the JS version mocks out fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的示例会生成以下 javascript 代码:
return this.Markdown = function() { /* ... */ }
行使该函数成为new
运算符。写作
可以解决问题。
添加:
这个答案提到JavaScript 中的对象构造算法
Your example results in the following javascript code:
The line
return this.Markdown = function() { /* ... */ }
makes the function the object returned by thenew
operator.Writing
fixes the problem.
Addition:
This answer mentions the algorithm for object construction in javascript
CoffeeScript 的隐式返回与
new
结合使用时可能会导致混乱。正如其他人指出的那样,您可以使用显式返回。另一种选择是使用class
,它创建一个没有隐式返回的函数(构造函数
):当然,在这种情况下可读性不太好,但作为一般规则,每当您使用
new
时,通过使用class
就可以省去很多麻烦。CoffeeScript's implicit returns can lead to mayhem when used in conjunction with
new
. As others have pointed out, you could use explicit returns. Another option is to useclass
, which creates a function (theconstructor
) with no implicit return:Of course, that's not very readable in this case, but as a general rule, you'll save yourself headaches by using
class
whenever you usenew
.您需要显式地为对象/类设置返回值,否则它将在创建新实例时返回成员函数。
JS FIDDLE
编译为:
You need to explicitly set a return value for your objects/classes or else it will return the member functions when creating a new instance.
JS FIDDLE
compiles to:
这就是 Coffeescript 给出的输出
每个函数的最后一行都会在 Coffeescript 中隐式返回。在控制台中检查这一点会产生 MarkdownDeep,
它返回一个没有 Markdown() 作为方法的函数。
This is what Coffeescript gives as output
The last line in every function is implicitly returned in Coffeescript. Checking this in the console yields MarkdownDeep as
which returns a function that does not have Markdown() as a method.
CoffeeScript 自动将每个输出文件包装在匿名函数中 (
(function() { ... })()
)。要禁用此功能,请在运行coffee
时使用--bare
或-b
选项。CoffeeScript automatically wraps each output file in an anonymous function (
(function() { ... })()
). To disable this use the--bare
or-b
option when runningcoffee
.