Настройка реквизита при определении нового экземпляра класса - PullRequest
0 голосов
/ 12 октября 2018

Я пытаюсь создать приложение для выставления счетов, используя машинопись.Я создал класс Invoice, который имеет три объекта в качестве свойств, и внутри этих объектов у них есть соответствующие реквизиты.В целях тестирования в конструкторе я передавал только реквизиты из объекта item.Я хочу создать экземпляр класса счета-фактуры и установить для объекта реквизита (в классе счета-фактуры) значение <input> значения входных тегов.Когда я тестировал только для того, чтобы увидеть, был ли создан экземпляр объекта, я продолжал получать эту ошибку:

Невозможно установить свойство 'цена' для undefined в новом счете

Вот мой код

// invoice class
class Invoice {
    // fields
    item: {
        price: number;
        partNumber: number;
        partDescription: string;
        quantity: number;
        pricePerItem: number;
        discountApplied: number;
    }

    invoiceState: {
        valid: {
            OK: boolean;
            NOTOK: boolean;
        },
        invalid: {
            price: number;
            inventory: number;
            name: string;
            country: string;
            quantity: number;
        }
    };

    country: {
        countryOrigin: {
            name: string;
            symbol: string;
            hasTaxRate: boolean;
        }

    };

    constructor(price: number, partNumber: number, quantity: number, pricePerItem: number, partDescription: string, discountApplied: number) {
        this.item.price = price;
        this.item.partNumber = partNumber;
        this.item.quantity = quantity;
        this.item.pricePerItem = pricePerItem;
        this.item.partDescription = partDescription;
        this.item.discountApplied = discountApplied;
    }

    // methods
    calcPrice() {

    }

    getInoviceAmount() {

    }
}

// testing
// want to put this var inside the AddItem button and deleteItem and this new instance to the object created
// create a new object tied to that element
let invoiceItem = new Invoice(1, 3, 5, 6, "part", 1);
console.log(invoiceItem);


//  add an item
let addedItem = document.getElementById("addItem").addEventListener("click", () => {
    let table = document.getElementById("table-contents");
    table.insertAdjacentHTML('beforeend', "<tr id='item-info'> <th scope='row'>1</th> <td><input type='text'></td> <td><input type='number'></td> <td><input type='number'></td> <td><input type='number'></td> <td><span></span></td></tr>");
});;

// delete item
let deleteItem = document.getElementById("deleteItem").addEventListener("click", () => {
    let row = document.getElementById("item-info");
    row.remove();
});

Вот мой HTML-код:

<table class="table table-striped table-dark invoice-table">
                <thead>
                    <tr class="head-contents">
                        <th scope="col">#</th>
                        <th scope="col-3">Description</th>
                        <th scope="col">Quanity</th>
                        <th scope="col">item number</th>
                        <th scope="col">Item price</th>
                        <th scope="col">total price</th>
                    </tr>
                </thead>
                <tbody id="table-contents">
                    <tr id="item-info">
                        <th scope="row">1</th>
                        <td><input type="text"></td>
                        <td><input type="number"></td>
                        <td><input type="number"></td>
                        <td><input type="number"></td>
                        <td>$<span>0.00</span></td>
                    </tr>
                </tbody>
            </table>

1 Ответ

0 голосов
/ 12 октября 2018

item еще не определено в ваших Invoice экземплярах.Создайте его как первую строку в конструкторе:

constructor(/* ... */) {
  this.item = {};
  /* ... */
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...