【问题标题】:How to implement references between objects in javascript如何在javascript中实现对象之间的引用
【发布时间】:2016-01-01 22:57:15
【问题描述】:

我正在寻找在 javascript 中存储对对象的引用的正确方法。

例如我有一个对象客户:

function Customer(n) {
  this.name = n;
}

还有一个由所有客户组成的数组,被填满:

var customers = new Array()
customers.push(new Customer('Alfred'));
customers.push(new Customer('Bob'));

现在我还有其他几个引用客户的对象,例如purchaseoutstandingOfferpromotion 等。这应该都引用客户数组的元素。例如:

function Purchase(i, c) {
  this.customer = c; // ? <- this need to be a reference
  this.item = i; 
}

这可以通过将索引存储在数组中来完成,但如果需要删除客户,这似乎很脆弱。在 javascript 中存储对另一个对象的引用的最佳方法是什么?

【问题讨论】:

    标签: javascript reference


    【解决方案1】:

    看看下面你的方法是不同的

    var customers = new Array()
    customers.push(new Customer('Alfred'));
    customers.push(new Customer('Bob'));
    

    您在数组中推送新对象而不保存对它的引用。因此您的购买功能永远不会知道谁是谁或谁是什么

    这就是我的处理方式

    function Customer(n) {
      this.name = n;
      this.items=[];
      this.addPurchase=function(item){
      this.items.push(item);
      }
    }
    

    上面的函数会有如下的

    1. 客户姓名
    2. 将商品添加到客户商品购物车的函数
    3. 商品购物车
    var customers = {}; //create a big object that stores all customers
    customers.Alfred=new Customer('Alfred'); // create a new object named Alfred
    customers.Bob=new Customer('Bob'); // create a new object named Bob
    customers.John=new Customer('John'); // create a new object named John
    

    使用console.log,你会得到

    Alfred: Object, Bob: Object, John: Object
    

    如果您想向 Alfred 添加项目,请执行此操作

    customers.Alfred.addPurchase('pineapple');
    

    如果您想向 Bob 添加项目,请执行此操作

    customers.Bob.addPurchase('mango');
    

    如果您想向 John 添加项目,请执行此操作

    customers.John.addPurchase('coconut');
    

    这是console.log(customers.John.items);的输出

    Array [ "coconut" ]
    

    如果我们想删除客户怎么办? 我们已经有了它的参考!

    delete customers.John;
    

    约翰,这段历史已经消失了!...验证它是否被删除

    console.log(customers);
    

    输出

    Object { Alfred: Object, Bob: Object }
    

    【讨论】:

      【解决方案2】:

      使用new 创建对象

      var customers = new Array()
      customers.push(new Customer('Alfred'));
      customers.push(new Customer('Bob'));
      
      function Purchase(i, c) {
        this.customer = c; // ? <- this need to be a reference
        this.item = i; 
      }
      
      var Purchase_obj = new Purchase(2,customers[0] );
      

      【讨论】:

      • 如果我更改了客户的姓名,是否会显示在购买中?当客户中的客户被删除时会发生什么?
      • @Beginner 如果您更新将反映在购买对象中的客户名称,这是 oop 的主要概念,如果您从客户数组中删除一个客户,它不会被销毁,您仍然可以获得购买对象中的客户名称
      猜你喜欢
      • 2023-01-10
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 2021-07-31
      • 2016-03-14
      相关资源
      最近更新 更多