我正在学习骨干,我有一个非常简单的问题,下面的代码工作正常:
var segments = Backbone.Model.extend({
url: url;
});
var segments = new Segments();
但如果我在扩展时放置新的,那么它不会。例如:
var segments = new Backbone.Model.extend({
url: url;
});
有人可以解释原因吗?
答案 0 :(得分:1)
关键字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
答案 1 :(得分:0)
这不是真正的骨干相关,而是更多的javascript。
在你的例子中:
var segments = new Backbone.Model.extend({
url: url
});
“new”运算符具有最高优先级,因此首先计算它(在执行Backbone.Model.extend()之前)。所以你真的试图从extend()函数中实例化一个对象,而不是它的返回值。
如果将其更改为:
,它应该有效var segments = new (Backbone.Model.extend({
url: url
}));
在这种情况下。 extend()函数首先被调用并返回一个对象(这是骨干中的模型定义)。
但这不是一个好习惯。您正在定义一个模型(在括号中)并将其丢弃(不将该定义保留在变量中)。
您可以在此处找到有关javascript运算符优先级的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
答案 2 :(得分:0)
您正在尝试实例化extend方法,该方法用于将属性复制到构造函数以供以后实例化。
这是扩展方法:
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({}),您只需使用提供的参数调用函数。