当使用 unit.js
库时,当我克隆具有名称为 "must"
的属性的简单 JSON 对象时,我发现了一个奇怪的行为。请参阅示例:
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
不会打印 result
的 must
属性,但它位于克隆对象中,因为 JSON .stringify
正在为 result.must
工作。如果我删除 unit.js
行,一切正常。 (我使用unit.js@0.1.8)
这是什么原因,unit.js 是否在 Object.prototype 中添加了一些东西?不管它是什么,它是一种保护我们的应用程序免受此类错误影响的方法吗?非常奇怪的是,第三方库会导致这样的错误。
如有任何帮助,我们将不胜感激!
Ps.:我使用了How do I correctly clone a JavaScript object?中建议的克隆功能但与 lodash 的 cloneDeep
方法也是一样的。
更新:
我尝试了更多查询:在结果
上使用for in
、in
、hasOwnProperty
:
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
循环中。
最佳答案
我已经在unit.js的github page上询问过了感谢 Nicolas Talle我已经得到了正确的答案。
总而言之,发生这种情况是因为 MustJS 将 must
添加为不可枚举属性(ShouldJS 的 should
也是如此)。我们可以通过添加以下内容来摆脱这个问题:
delete Object.prototype.must;
delete Object.prototype.should;
详细答案请参阅问题:https://github.com/unitjs/unit.js/issues/6
Unit.js的文档也按照这个进行了扩展:http://unitjs.com/guide/must-js.html
关于javascript - 使用unit.js库时克隆对象的工作很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27233943/