当使用单元.js库时,克隆对象的工作方式很奇怪

Cloning objects works strange when unit.js library is used

本文关键字:工作 对象 方式 单元 js 库时      更新时间:2023-09-26
当我

克隆简单的 JSON 对象时,我发现了一种奇怪的行为,该对象的属性名称是 "must" 当使用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行,一切都很好。(我用单位.js@0.1.8(

这是什么原因,单位.js是否为Object.prototype添加了一些东西?不管它是什么,它是否是一种保护我们的应用程序免受此类错误侵害的方法?非常奇怪的是,第三方库会导致这样的错误。

任何帮助将不胜感激!

Ps.:我使用了如何正确克隆 JavaScript 对象中建议的克隆函数? 但 Lodash 的 cloneDeep 方法也是如此。

更新:

我尝试了更多查询:在result上使用for ininhasOwnProperty

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页面上问过它,感谢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