我开始用 backbone 学习 javascript/coffeescript,但我遇到了一个我不明白的错误。任何帮助将不胜感激。
我做了一个非常简单的示例,使用以下 buggy.coffee
coffeescript 文件:
class Panel extends Backbone.Model
p = Panel() # I instantiate it to trigger the error
我使用 coffee -c buggy.coffee
编译成 buggy.js
。但是当我运行它并查看 javascript 控制台时,我得到了错误:
Uncaught TypeError: undefined is not a function
错误发生在 backbone.js(第 256 行)::
var Model = Backbone.Model = function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
this.set(attrs, options); ### <================================== here
this.changed = {};
this.initialize.apply(this, arguments);
};
因为 this.set
是未定义的。
现在我找到了一种通过编辑 buggy.js
来避免错误的方法(注释是原始的 coffeescript 生成行):
function Panel() {
#return Panel.__super__.constructor.apply(this, arguments);
return new Panel.__super__.constructor(this, arguments);
}
但这不是真正的解决方案。 那么我做错了什么?
最佳答案
在 JavaScript 中实例化对象时,必须使用 new
关键字。 p = Panel()
失败,但 p = new Panel()
可以。
如果您不包含 new
关键字,则 this
不会绑定(bind)到新对象。相反,它会绑定(bind)到全局对象。因此,您不会创建新的 Panel
,而是破坏全局对象的属性。您还将调用该全局对象(例如,如果您编写 this.func()
)而不是在您的面板上,这可能是此错误显示为“undefined is not a”的原因功能”。
关于javascript - 使用 coffeescript 生成的 js 未捕获的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25099887/