答案:
事实证明,我在创建类实例时忽略了使用 new
关键字。问题本身的代码很好。
问题:
我有一个相当简单的类,其中构造函数调用该类的另一个方法(editor_for_node)。该调用发生在 jQueryeach() 循环内,但我也尝试将其移到外部。
define ['jquery'], ($) ->
class Editor
constructor: (@node, @data, @template) ->
@node.widgets().each (i, elem) =>
data = if @data then @data[i] else null
node = $(elem)
@editor_for_node node, data
editor_for_node: (node, data) ->
console.log 'hello!'
return {
'Editor': Editor,
}
当调用 @editor_for_node node, data
行时,我收到一条错误(在 Firebug 中),提示 this.editor_for_node 不是函数
。
我真的不明白为什么这不能正常工作,我能看到的唯一可能的奇怪来源是我在开始时使用了 require.js 的定义函数。
编辑:生成的输出
(function() {
define(['jquery'], function($) {
var Editor;
Editor = (function() {
Editor.name = 'Editor';
function Editor(node, data, template) {
var _this = this;
this.node = node;
this.data = data;
this.template = template;
this.node.widgets().each(function(i, elem) {
data = _this.data ? _this.data[i] : null;
node = $(elem);
return _this.editor_for_node(node, data);
});
}
Editor.prototype.editor_for_node = function(node, data) {
return console.log('hello!');
};
return Editor;
})();
return {
'Editor': Editor
};
});
}).call(this);
最佳答案
首先:您使用的是哪个版本的 CoffeeScript?粗箭头一直是某些先前版本中错误的来源。
如果您使用的是最新版本(1.3.1),那么我将继续说这是一个缩进问题。当我复制并粘贴您的代码时,它工作正常。您是否混合使用制表符和空格?验证编译的输出是否包含行
Editor.prototype.editor_for_node = ...
更新:请参阅对此答案的评论。结果发现问题是调用构造函数时没有使用 new
关键字。
关于coffeescript - 无法识别构造函数中调用类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10536304/