2012-07-25 40 views
2

我一直在使用jQuery.extend更換這樣從JavaScript中另一個對象的屬性更換對象的屬性,沒有圖書館

var Car = function(options){ 
    var defaultOptions = { 
     color: "hotpink", 
     seats: { 
      material: "fur", 
      color: "black", 
      count: 4 
     }, 
     wheels: 4 
    } 
    this.options = $.extend(true,{},defaultOptions,options); 
} 

var myCar = new Car({ 
    color: "blue", 
    seats: { 
     count: 2, 
     material: "leather" 
    } 
}); 

alert(myCar.options.color); // "blue" 
alert(myCar.options.seats.color); // "black" 
alert(myCar.options.seats.count); // 2 

默認屬性雖然它的偉大工程,我想知道最好的沒有任何圖書館的方式來實現類似的結果我只是想在函數中定義一些默認設置,並用參數中的設置替換它們,每次我這樣做時都會包含一個庫來矯枉過正。

回答

4

基本上它只是for..in的遞歸使用。你可以看到jQuery實現的完整源代碼in the source code(這個行號會隨着時間的推移而變壞,但它可能會保留在core.js之內)。

這裏是一個非常基本的現成的,袖口:

function deepCopy(src, dest) { 
    var name, 
     value, 
     isArray, 
     toString = Object.prototype.toString; 

    // If no `dest`, create one 
    if (!dest) { 
     isArray = toString.call(src) === "[object Array]"; 
     if (isArray) { 
      dest = []; 
      dest.length = src.length; 
     } 
     else { // You could have lots of checks here for other types of objects 
      dest = {}; 
     } 
    } 

    // Loop through the props 
    for (name in src) { 
     // If you don't want to copy inherited properties, add a `hasOwnProperty` check here 
     // In our case, we only do that for arrays, but it depends on your needs 
     if (!isArray || src.hasOwnProperty(name)) { 
      value = src[name]; 
      if (typeof value === "object") { 
       // Recurse 
       value = deepCopy(value); 
      } 
      dest[name] = value; 
     } 
    } 

    return dest; 
} 
+0

如果OP想要保留API,那麼jQuery是一個好的開始,但是如果OP準備改變(簡化)API,則構建的擴展可以更短,更高效和更健壯(例如,jQuery * isPlainObject *非常普通而且不必要,* isFunction *或* isArray *)也是如此。 – RobG 2012-07-25 09:52:26

+0

RobG說,jQuery實現看起來像是一個相當多的代碼。我想知道是否有任何解決方法或解決此問題的其他方法。 – user1463028 2012-07-26 09:43:32

+1

我試圖做一個易於使用的,獨立的代碼片段,基本上只有一個函數,裏面有幾個方法。有點像jQuery插件,但不依賴於jQuery。 我想讓用戶在一個單一的對象中定義所有的選項爲了可讀的代碼,但我想定義一切的默認值,所以用戶不需要改變任何東西,如果他對默認值滿意外觀和功能。 – user1463028 2012-07-26 09:53:51

0

可以效仿jQuery的API「擴展」,就像樓上說。我認爲沒有更好的辦法來做到這一點。所以,我認爲jQuery的API是適當的。