Backbone.js怀疑

fel*_*lix 0 javascript backbone.js

我有以下父对象:

Context = {
   ContextModel: Backbone.Model.extend({
      //model Code
   }),
   ContextList:Backbone.Collection.extend({
      model : Context.ContextModel
      // collection Code
   }),
   Contexts: new Context.ContextList,
   ContextView: Backbone.View.extend({
      // view Code
   }) 
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,model : Context.ContextModel抛出一个错误说Uncaught ReferenceError: Context is not defined.我已经定义了Context对象,但不知何故它没有看到它.请有人帮帮我.谢谢

ick*_*fay 5

让我们来看看JavaScript解释器的眼睛.你有一个声明,Context = { ... }.为了执行该语句,它必须首先构造{ ... }它以便将其分配给它Context.为了构建{ ... }它,需要进行评估new Context.ContextList.不幸的是,它仍在构建该{ ... }部分,尚未分配任何东西Context.因此,Context当您尝试创建新实例时未定义Context.ContextList.您Context.ContextModel在创建时尝试访问时遇到同样的问题Context.ContextList.试试这个:

Context = {
   ContextModel: Backbone.Model.extend({
      //model Code
   }),
   ContextView: Backbone.View.extend({
      // view Code
   }) 
}
Context.ContextList=Backbone.Collection.extend({
    model : Context.ContextModel
    // collection Code
});
Context.Contexts=new Context.ContextList();
Run Code Online (Sandbox Code Playgroud)