对象构造函数语法错误

时间:2016-02-05 21:58:07

标签: javascript

在学习JS的过程中...从JS的第一天起第二周,我就有了语法上的大问题

function Customer(name, street, city, state, email, balance) {
    this.name = name;
    this.street = street;
    this.city = city;
    this.state = state;
    this.email = email;
    this.balance = balance;
    this.payDownBal = function(amtPaid) {
        this.balance -= amtPaid;
    };
    this.addToBa = function(amtCharged) {
        this.balance += amtCharged;
    };
}
var cust2 = new Customer("Sally Smith", "234 Main ", "Pittsburgh", "PA", "ssmith@aol.com", 0.00);

cust2.addToBal(15.50);

Customer.prototype.isCreditAvail = true;

Customer.prototype.toString = function() {
    return this.name + " lives at " + this.street + " in " +
        this.city + " " + this.state + " email : " + this.email +
        " and has a balance of $ " + this.balance.toFixed(2) + "Creditworty : " + this.isCredAvail;
}
document.write(cust2.toString());

我找不到错误......我可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

那么,仔细看看第11行,你的函数声明:

this.addToBa = function (amtCharged) {

和第17行:

cust2.addToBal(15.50);

这是一个错字,第11行的“addToBa”应该是“addToBal”。

(另外,还有另一个拼写错误,不允许在你的toString函数中引用“isCreditAvail”TRUE布尔值,在第3行到最后一行...将“this.isCredAvail”更改为“this。 isCreditAvail“)。

答案 1 :(得分:1)

你犯了一个简单的错误。 您定义了 addToBa()函数,并且您正在调用未定义的函数 addToBal()

更改第17行以调用函数 addToBa()。 (或将函数声明更改为 addToBal())。