简体   繁体   English

实例冲突-JSON对象

[英]Instances Conflicting - JSON objects

I'm not doing something right. 我做的不对。

Trying to create 2 instances of data models off my json model template file and use them but I'm obviously not getting 2 different instances of the model. 尝试从json模型模板文件创建2个数据模型实例并使用它们,但显然我没有得到2个不同的模型实例。

myModel.json myModel.json

{
    "id": null
}

myNodeModule.js myNodeModule.js

var myModel = require('../../entities/myModel');

module.exports = {

    find: function *(id){
        var myModelInstance1 = myModel;
        myModelInstance1.id = 1;

        var myModelInstance12 = myModel;
        myModelInstance12.id = 2;

        found.push(myModelInstance11);
        found.push(myModelInstance12);

        console.log("id: " + found[0].id);
}

Problem : it logs "2" because for some reason it applies the last initialization for myModel1. 问题 :它记录“ 2”,因为由于某种原因,它对myModel1应用了最后的初始化。

So how do you create 2 separate object instances of myModel.json? 那么,如何创建2个独立的myModel.json对象实例?

Create a function instead, which returns the object and call it. 而是创建一个函数,该函数返回对象并调用它。

function myModelFact(){
  return {
      "id": null
  }
}

The problem is that requiring a JSON document creates an object instance, but returns a reference to that instance (objects are passed/assigned by reference). 问题在于,需要JSON文档创建对象实例,但返回对该实例的引用(对象通过引用传递/分配)。 That means that when you assign myModel , which is a reference to the object to another variable, you are essentially assigning a pointer to that same object. 这意味着,当您将对对象的引用myModel分配给另一个变量时,实际上是在分配指向该对象的指针。 Consequently, if you modify the reference, the single instance changes and that change reflects on all references to that instance. 因此,如果您修改引用,则单个实例会更改,并且该更改会反映对该实例的所有引用。

Try something like this instead: 尝试这样的事情:

function _getModelInstance() {
    return require('../../entities/myModel');
}

module.exports = {

    find: function(id){
        var myModelInstance1 = _getModelInstance();
        myModelInstance1.id = 1;

        var myModelInstance12 = _getModelInstance();
        myModelInstance12.id = 2;

        found.push(myModelInstance11);
        found.push(myModelInstance12);

        console.log("id: " + found[0].id);
}

This code will create a new instance of the object from the JSON document on demand. 此代码将根据需要从JSON文档创建该对象的新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM