骨干模型新实例



我正在学习主干,我有一个非常简单的问题,下面的代码运行良好:

var segments = Backbone.Model.extend({
    url: url; 
});
var segments = new Segments();

但如果我在扩展的同时放入新的,那么它就不会了。例如:

 var segments = new Backbone.Model.extend({
        url: url; 
  });

有人能解释一下原因吗?

关键字new用于实例化模型,而不是定义或扩展它。所以

var Segments = Backbone.Model.extend({   /// Capitalize your model definition
   url: url  // no semicolon here
});  ///here you are defining a regular Backbone Model

var OtherSegments = Segments.extend({
    url: url
});  ///here you are extending your model
var segments = new Segments();  //this is how you instanciate a BB model 
                                //and use lower case to differentiate the definition 
                                //for the instanciation set to  variable.
var otherSegments = new OtherSegments(); 
var mySegments = new Segments({ url : url}); // you can pass values at the time of 
                                             //instanciatation

这并不是真正的主干网相关,而是更多的javascript。

在您的示例中:

var segments = new Backbone.Model.extend({
  url: url
});

"new"运算符具有最高优先级,因此它首先进行求值(在执行Backbone.Model.exextend()之前)。因此,您实际上是在尝试从extend()函数实例化对象,而不是它的返回值。

如果您将其更改为:,它应该可以工作

var segments = new (Backbone.Model.extend({
  url: url
}));

在这种情况下。extend()函数首先被调用并返回一个对象(这是主干中的模型定义)。

但这不是一个好的做法。您正在定义一个模型(在括号中),同时将其丢弃(不将定义保留在变量中)。

您可以在这里找到更多关于javascript运算符优先级的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

您正在尝试实例化扩展方法,该方法用于将属性复制到构造函数中,以便稍后进行实例化。

以下是扩展方法:

var extend = function(protoProps, staticProps) {
1520     var parent = this;
1521     var child;
1522 
1523     // The constructor function for the new subclass is either defined by you
1524     // (the "constructor" property in your `extend` definition), or defaulted
1525     // by us to simply call the parent's constructor.
1526     if (protoProps && _.has(protoProps, 'constructor')) {
1527       child = protoProps.constructor;
1528     } else {
1529       child = function(){ return parent.apply(this, arguments); };
1530     }
1531 
1532     // Add static properties to the constructor function, if supplied.
1533     _.extend(child, parent, staticProps);
1534 
1535     // Set the prototype chain to inherit from `parent`, without calling
1536     // `parent`'s constructor function.
1537     var Surrogate = function(){ this.constructor = child; };
1538     Surrogate.prototype = parent.prototype;
1539     child.prototype = new Surrogate;
1540 
1541     // Add prototype properties (instance properties) to the subclass,
1542     // if supplied.
1543     if (protoProps) _.extend(child.prototype, protoProps);
1544 
1545     // Set a convenience property in case the parent's prototype is needed
1546     // later.
1547     child.__super__ = parent.prototype;
1548 
1549     return child;
1550   };

使用Backbone.Model.extend({}),您只是在调用一个带有参数的函数。

最新更新