2014-12-01 59 views
1

當我使用unit.js庫時,我使用名稱爲"must"的屬性克隆簡單的JSON對象時,發現了一個奇怪的行爲。見例如:當使用unit.js庫時,克隆對象的工作很奇怪

var test = require("unit.js"); // delete this line and the result will be good 

var input = { 
    "parameter": "value", 
    "must": { 
     "parameter_in": "value_in" 
    } 
}; 

console.log("Input: " + JSON.stringify(input, undefined, 2)); 
var result = clone(input); 
console.log("Result: " + JSON.stringify(result, undefined, 2)); // no "must" element 
console.log("Result (must): " + JSON.stringify(result.must, undefined, 2)); 

function clone(obj) { 
    var copy; 

    // Handle the 3 simple types, and null or undefined 
    if (null == obj || "object" != typeof obj) return obj; 

    // Handle Date 
    if (obj instanceof Date) { 
     copy = new Date(); 
     copy.setTime(obj.getTime()); 
     return copy; 
    } 

    // Handle Array 
    if (obj instanceof Array) { 
     copy = []; 
     for (var i = 0, len = obj.length; i < len; i++) { 
      copy[i] = clone(obj[i]); 
     } 
     return copy; 
    } 

    // Handle Object 
    if (obj instanceof Object) { 
     copy = {}; 
     for (var attr in obj) { 
      if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); 
     } 
     return copy; 
    } 

    throw new Error("Unable to copy obj! Its type isn't supported."); 
} 

結果:

Input: { 
    "parameter": "value", 
    "must": { 
    "parameter_in": "value_in" 
    } 
} 
Result: { 
    "parameter": "value" 
} 
Result (must): { 
    "parameter_in": "value_in" 
} 

JSON.stringify不打印的resultmust屬性,但它是在克隆的對象,因爲JSON.stringify正在爲result.must。如果我刪除了unit.js行,一切都很好。 (我使用[email protected]

這是什麼原因,unit.js是否在Object.prototype中添加了一些東西?不管它是什麼,它是一種保護我們的應用程序免受這種錯誤的方式嗎?非常奇怪的是,第三方庫可能導致這樣的錯誤。

任何幫助,將不勝感激!

Ps .:我使用了How do I correctly clone a JavaScript object?中建議的克隆函數,但它也與lodash的cloneDeep方法相同。

更新:

我已經嘗試了一些更多的查詢:使用for ininhasOwnPropertyresult

console.log("\"must\" is in: " + ('must' in result)); 
console.log("\"must\" is with hasOwnProperty: " + result.hasOwnProperty("must")); 
console.log("In properties:"); 
for (var property in result){ 
    console.log("\tproperty: " + property); 
} 

結果與unit.js

"must" is in: true 
"must" is with hasOwnProperty: true 
In properties: 
     property: parameter 

所以must屬性沒有隻出現在for in循環中。

回答