我开始学习带骨干的javascript / coffeescript,我收到了一个我不明白的错误。任何帮助将不胜感激。
我使用以下buggy.coffee
coffeescript文件制作了一个非常简单的示例:
class Panel extends Backbone.Model
p = Panel() # I instantiate it to trigger the error
我使用buggy.js
编译成coffee -c buggy.coffee
。但是当我运行它并查看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);
}
但这不是一个真正的解决方案。 那么我做错了什么?
答案 0 :(得分:2)
在JavaScript中实例化对象时,必须使用new
关键字。 p = Panel()
失败,但p = new Panel()
会有效。
如果您不包含new
关键字,则this
不会绑定到新对象。相反,它会绑定到全局对象。因此,您不必创建新的Panel
,而是在全局对象上破坏属性。您也将在该全局对象上进行调用(例如,如果您编写this.func()
)而不是在Panel上,这可能是此错误显示为&#34;未定义不是函数的原因&#34 34 ;.