简体   繁体   中英

Pass object property value to another property within that object in Typescript Angular

I have this big object in TypeScript and I'm trying to make some aspects of it automatic, to save me time.

myObject = [
    {
      id: 0,
      price: 100,
      isBought: false,
      click: () => this.buyItem(100, 0)
    }
buyItem (itemCost: number, itemIndex: number) {
    if (this.money >= itemCost) {
      this.myObject[itemIndex].isBought = true;
    }

I've already managed to automatically increment the id property with this function:

findIndex() {
    var objLength = Object.keys(this.myObject).length;
    for(let i=0; i<objLength; i++) {
      this.myObject[i].id = i;
    }
  }

But what I can't do is pass property values inside the object itself. In theory this is what I'm looking for.

myObject = [
    {
      id: 0,
      price: 100,
      isBought: false,
      click: () => this.buyItem(THIS.PRICE, THIS.ID)
    }

Is this possible? And if not, are there any workarounds? Thank you.

What about this approach?

function ItemModel (price) {
    let self = this;

    self.id = 0;
    self.price = price;
    self.isBought = false;

    self.click = () => {
        buyItem(self.price, self.id);  
    };
}

var newInstanceOfItem = new ItemModel(100); // price is 100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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