[英]How to assign an object to a class property in javascript
Create a class called Vending Machine (VM) that returns an instance of a vending machine.创建一个名为 Vending Machine (VM) 的类,它返回一个自动售货机的实例。 The Vending Machine instance contains an inventory property which is an object that holds the name of inventory items and the total amount of stock of each item.
Vending Machine 实例包含一个inventory 属性,它是一个对象,其中包含库存物品的名称和每个物品的库存总量。
drinkInventory = {
1: { name: 'Sunny Delight', stock: 5 },
2: { name: 'Diet Soda', stock: 3 },
3: { name: 'Bottled Water', stock: 4 },
};
class VM {
constructor(obj) {
this.iventory = Object.assign(this, obj);
}
}
I'm trying to pass in drinkInventory我正在尝试传入drinkInventory
the more simple is this.iventory = JSON.parse(JSON.stringify(obj))
更简单的是
this.iventory = JSON.parse(JSON.stringify(obj))
const drinkInventory= { 1: { name: 'Sunny Delight', stock: 5 } , 2: { name: 'Diet Soda', stock: 3 } , 3: { name: 'Bottled Water', stock: 4 } }; class VM { constructor(obj) { this.iventory = JSON.parse(JSON.stringify(obj)) } getStock(key) { return this.iventory[key].stock } } let bob = new VM(drinkInventory); drinkInventory['2'].stock = 50; console.log( 'bob stock 2 =', bob.getStock(2) );
You can also use Spread syntax => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax您还可以使用 Spread 语法 => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const drinkInventory= { 1: { name: 'Sunny Delight', stock: 5 } , 2: { name: 'Diet Soda', stock: 3 } , 3: { name: 'Bottled Water', stock: 4 } }; class VM { constructor(obj) { this.iventory = { ...obj }; // then repeat copy for first level of object entanglement for (let elm in obj ) { this.iventory[elm] = { ...obj[elm] } } } getStock(key) { return this.iventory[key].stock } } let bob = new VM(drinkInventory); drinkInventory['2'].stock = 50; console.log( 'bob stock 2 =', bob.getStock(2) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.