如何在javascript中实现对象之间的引用

How to implement references between objects in javascript

本文关键字:对象 之间 引用 实现 javascript      更新时间:2023-09-26

我正在寻找在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中存储对另一个对象的引用的最佳方式是什么?

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

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 }

使用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] );