2013-11-20 258 views
0

我學習骨幹,我有一個非常簡單的問題,下面的代碼工作正常:骨幹模型新實例

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

var segments = new Segments(); 

,但如果我同時延長提出了新的則沒有。例如:

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

有人可以解釋爲什麼嗎?

+0

其實,你的代碼有語法錯誤(';'),並嘗試把一對括號在你的第二個例子... –

回答

1

關鍵字新用於實例化的模型不定義它或擴展它。 所以

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 
+0

我只是固定的,真不錯,我複製,恕不另行通知該貼。謝謝 –

0

這不是真的骨幹相關,但一般更多的JavaScript。

在您的例子:

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

「新」 運算符的優先級最高,所以它首先計算(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

0

你試圖實例擴展方法,它是用來屬性複製到供以後實例化一個構造函數。

這裏是擴展方法:

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({})你只是調用一個函數,所提供的參數。