JavaScript:如何修复未正确分配属性值的实例

时间:2019-04-21 03:21:47

标签: javascript class oop object properties

我创建了一个Piece类的实例,并试图打印该实例的quantity的值,但是我一直都没有得到定义。

我在Google Chrome控制台中查看,console.log(temp)很好,但是在我看来它没有被分配任何属性值。 (我相信,如果您单击实例的下拉箭头,它应该显示属性和值,对吗?)

我也console.log(length)console.log(quantity)都可以正常打印。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Parker Steel Program</title>
    <link rel="stylesheet" href="./main.css">
    <script src="./form.js"></script>
    <script src="./order.js"></script>
</head>
<body>
    <h1>Parker Steel Company</h1>
    <h2>New Order</h2>
    <form id="order-info">
        <label for="stock-length">Stock Length:</label>
        <input autofocus="true" id="stock-length" name="stock-length" required="true" type="number">
        <fieldset id="line1" name="line-1">
            <label for="line-1-length">Length: </label>
            <input id="line-1-length" name="line-1-length" required="true" type="number">
            <label for="line-1-quantity">Quantity: </label>
            <input id="line-1-quantity" name="line-1-quantity" required="true" type="number">
            <button onclick="removePurchaseLine('line1')" type="button">Remove</button>
        </fieldset>
        <button id="add-purchase-line" name="add-purchase-line" onclick="addPurchaseLine()" type="button">Add Purchase Line</button>
        <button onclick="getBestCuttingSequence()" type="button">Calculate</button>
    </form>
</body>
</html>
class Piece {
    constuctor(length, quantity) {
        this.length = length;
        this.quantity = quantity;
    }
}

function getBestCuttingSequence() {
    const stockLength = document.getElementById("stock-length").value;
    const pieces = getPieces();
}

function getPieces() {
    const pieces = []
    const numPurchaseLines = document.getElementsByTagName("fieldset").length; 

    for (let purchaseLine = 1; purchaseLine <= numPurchaseLines; purchaseLine++) {
        let length = document.getElementById(`line-${purchaseLine}-length`).value;
        let quantity = document.getElementById(`line-${purchaseLine}-quantity`).value;
        let temp = new Piece(length, quantity);
        console.log(temp.length);
    }

    return pieces;
}

最终,我将这些实例推送到pieces数组中,然后在以后使用它们。

我的预期结果将只能是console.log(temp.quantity)并将其打印出来。

当前正在打印未定义的内容。

编辑:更改属性名称。

1 个答案:

答案 0 :(得分:1)

几乎没有错字。 constuctor缺少r。更改它将起作用。

不过,您可以在不进行修改的情况下向this添加属性,则可以先传递对象,然后传递Object.assign

class Piece {
    constructor(obj) {
        Object.assign(this,obj);
    }
}

像这样通过

let temp = new Piece({length, quantity});