在我看来,你不明白什么是闭包,以及如何使用IIFE。
你有几个选择去做你想做的事。
起初,您可以只使用全局对象来跨文件共享对象。像这样:
// model.js
(function(exports, Backbone, undefined) {
var Model = Backbone.Model.extend({});
exports.Model = Model;
})(window, Backbone);
// collection.js
(function(exports, Backbone, _, undefined) {
var Model = exports.Model;
var Collection = Backbone.Collection.extend({
model: Model
// ...
});
exports.Collection = Collection;
})(window, Backbone, _);
或这个:
// model.js
Model = (function(Backbone, undefined) {
var Model = Backbone.Model.extend({});
return Model;
})(Backbone);
// collection.js
Collection = (function(Backbone, _, undefined) {
var Collection = Backbone.Collection.extend({
model: Model
// ...
});
return Collection;
})(Backbone, _);
或者,您可以在全局空间中创建一个对象并将其用作命名空间。
// model.js
(function(App, Backbone, undefined) {
var Model = Backbone.Model.extend({});
App.Model = Model;
})(App = (window.App || {}), Backbone);
// collection.js
(function(App, Backbone, _, undefined) {
var Model = App.Model;
var Collection = Backbone.Collection.extend({
model: Model
// ...
});
App.Collection = Collection;
})(App = (window.App || {}), Backbone, _);
或者您可以将您的对象定义为AMD 模块,然后使用任何 AMD 加载程序。例如,如果你想使用 require.js,你可以这样写:
// main.js
require.config({
paths: {
'jquery': '/js/vendor/jquery.js',
'underscore': '/js/vendor/underscore.js',
'backbone': '/js/vendor/backbone.js',
'model': '/js/model.js',
'collection': '/js/collection.js'
},
shim: {
backbone: {
deps: ["underscore", "jquery"],
exports: "Backbone"
},
underscore: {
exports: "_"
}
}
});
// model.js
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone){
var Model = Backbone.Model.extend({});
return Model;
});
// collection.js
define([
'jquery',
'underscore',
'backbone',
'model'
], function($, _, Backbone, Model){
var Collection = Backbone.Collection.extend({
model: Model
});
return Collection;
});