>我正在尝试在项目中使用Backbone-relational 和CoffeeScript。以下是我尝试建模的CoffeeScript中的一个例子:
class NestedModel extends Backbone.RelationalModel
defaults:
Description: 'A nested model'
NestedModel.setup()
class MainModel extends Backbone.RelationalModel
defaults:
Description: 'A MainModel description'
StartDate: null
relations: [
type: Backbone.HasOne
key: 'nestedmodel'
relatedModel: 'NestedModel'
includeInJSON: '_id'
reverseRelation:
type: Backbone.HasOne
includeInJSON: '_id'
key: 'mainmodel'
]
MainModel.setup()
nm = new NestedModel()
mm = new MainModel(nestedmodel: nm)
console.log mm.get("nestedmodel").get("mainmodel").get("Description")
return
CoffeeScript 生成以下 JavaScript:
var MainModel, NestedModel, mm, nm;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
NestedModel = (function() {
__extends(NestedModel, Backbone.RelationalModel);
function NestedModel() {
NestedModel.__super__.constructor.apply(this, arguments);
}
NestedModel.prototype.defaults = {
Description: 'A nested model'
};
return NestedModel;
})();
NestedModel.setup();
MainModel = (function() {
__extends(MainModel, Backbone.RelationalModel);
function MainModel() {
MainModel.__super__.constructor.apply(this, arguments);
}
MainModel.prototype.defaults = {
Description: 'A MainModel description',
StartDate: null
};
MainModel.prototype.relations = [
{
type: Backbone.HasOne,
key: 'nestedmodel',
relatedModel: 'NestedModel',
includeInJSON: '_id',
reverseRelation: {
type: Backbone.HasOne,
includeInJSON: '_id',
key: 'mainmodel'
}
}
];
return MainModel;
})();
MainModel.setup();
nm = new NestedModel();
mm = new MainModel({
nestedmodel: nm
});
console.log(mm.get("nestedmodel").get("mainmodel").get("Description"));
return;
这会产生以下警告和错误
Warning:
Relation= child
; no model, key or relatedModel (function MainModel() {
MainModel.__super__.constructor.apply(this, arguments);
}, "nestedmodel", undefined)
Error:
Uncaught TypeError: Cannot call method 'get' of undefined
只需从生成的 JavaScript 的第一行中删除"NestedModel"变量
var MainModel, NestedModel, mm, nm;
导致正确的行为。显然,我无法继续从生成的JavaScript中删除变量定义。我做错了什么?
好的,这似乎是一个范围界定问题。请参阅下面的 jsFiddle 示例。但是为什么我不能只引用本地函数作用域中的类呢?
但是为什么我不能只引用本地函数作用域中的类呢?
类作为立即调用的函数表达式实现
理解设计模式(如立即调用的函数表达式(的关键是要意识到 JavaScript 具有函数作用域(但不是块作用域(,并在闭包内通过引用传递值。
引用
- 立即调用的函数表达式