对象函数在JS中不起作用

时间:2016-02-03 12:14:17

标签: javascript function oop object functional-programming

这是一个简单的购物应用程序(有点)的功能,我根据我的基本经验编写了我的JS技能。但除了一件事之外,一切都有效:

applyStaffDiscount函数似乎不起作用。每当我尝试应用员工折扣时,程序只会返回与尝试应用折扣之前相同的原始值。请帮助,也让我知道如何改进这个程序。

function StaffMember(name, discountPercent) {
    this.name = name;
    this.discountPercent = discountPercent;
}

var sally = new StaffMember("sally", 5);
var bob = new StaffMember("bob", 10);
var arhum = new StaffMember("arhum", 20);

var cashRegister = {
    total: 0,
    lastTransactionAmount: 0,
    add: function(itemCost) {
        this.total += (itemCost || 0);
        this.lastTransactionAmount = itemCost;
    },
    scan: function(item, quantity) {
        switch (item) {
            case "eggs": this.add(0.98 * quantity); break;
            case "milk": this.add(1.23 * quantity); break;
            case "magazine": this.add(4.99 * quantity); break;
            case "chocolate": this.add(0.45 * quantity); break;
        }
        return true;
    },
    voidLastTransaction: function() {
        this.total -= this.lastTransactionAmount;
        this.lastTransactionAmount = 0;
    },
    applyStaffDiscount: function(employee) {
        this.total -= (this.total * (employee.discountPercent/100))
    }
};

    var cont = confirm("Are you ready to shop?")
    while (cont) {
        var user = ("Choose your function: A to Add Item, ED for Employee Discount, VT to Void Transaction or just X to Close")
        var askUser = prompt(user).toUpperCase()
        if (askUser === "A") {
            var itemName = prompt("What item would you like?", "Eggs, Milk, Magazine, Chocolate").toLowerCase()
            var itemNum = prompt("How many?")
            cashRegister.scan(itemName, itemNum)
            var cont = confirm("Your total bill is $" + cashRegister.total.toFixed(2) + ". Would you like anything else?")
        }
        else if (askUser === "ED") {
            var name1 = prompt("Please enter you name").toLowerCase()
            cashRegister.applyStaffDiscount[name1]
            alert("Your total bill is $" + cashRegister.total.toFixed(2) + ".")
}
        else if (askUser === "VT") {
            cashRegister.voidLastTransaction()
            alert("Your previous transaction has been voided. Your total bill is $" + cashRegister.total.toFixed(2) + " now.")
        }
        else if (askUser === "X") {
            cont = false
        }
        if (cont === false) {
            alert("We hope you had a good time. have a nice day!")
        }
    }

2 个答案:

答案 0 :(得分:1)

你没有在这里调用该函数:

cashRegister.applyStaffDiscount[name1]

尝试使用类似的东西:

cashRegister.applyStaffDiscount(name1);

答案 1 :(得分:1)

调用applyStaffDiscount应如下所示

cashRegister.applyStaffDiscount(name1);

然后在applyStaffDiscount函数内部,应按如下方式访问

this.total -= (this.total * (window[employee].discountPercent/100))