gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:01:32 25 4
gpt4 key购买 nike

我正在寻找在 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 }

关于javascript - javascript中如何实现对象之间的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34560875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com