-2

我对 Javascript 编程并不陌生,但我无法理解它是原型对象,不管是继承。当我试图通过这些东西工作时,我需要问代码什么问题才能解决这个问题。

4

2 回答 2

1

在 JavaScript 中使用“基于类”的对象创建:

var Wallet = function (pin, starting_balance, overdraft) {
    this.amount = starting_balance;
    this.pin = pin;
    this.overdraft = overdraft;
};


Wallet.prototype.addFunds = function (amount) {
    this.amound += amount;
};

Wallet.prototype.withdrawFunds = function (amount) {
    if (this.amount + this.overdraft >= amount) {
        this.amount -= amount;
        return new Wallet(this.pin, amount, this.overdraft);
    }
};

Wallet.prototype.displayBalance = function () {
    var cents = this.amount % 100,
        dollars = (this.amount - cents) / 100,
        total = dollars + "." + (cents > 9 ? cents : ("0" + cents));

    var output = "Current Balance: $" + total;
};



var myWallet = new Wallet(1234, 2000, 100000);
myWallet.displayBalance(); // "Current Balance: $20.00"

通过在返回的函数new上使用运算符,我可以修改构造函数的 。constructorthisprototype

即:修改Wallet.prototype.

然后,所有Wallets 都具有相同的功能。

当然,这不是一个非常安全的钱包。世界上任何人都可能出现并改变myWallet.amountmyWallet.pin

但如果我让钱包更安全:

var Wallet = function (pin, amount, overdraft) {
    var balance = amount,
        keyCode = pin,
        padding = overdraft;
};

Wallet.prototype.depositFunds = function (amount) { balance += amount; }; // does NOT work

这行不通。原型只能访问构造函数返回的对象的公共属性

这意味着Obj.prototype.<whatever>只能通过this.<whatever> = <x>;在构造函数中或事后手动添加某些东西来访问添加到对象中的内容myObj.property = <x>;

于 2012-09-19T04:14:23.873 回答
0

这篇博文,Understanding JavaScript Prototypes,真的帮助我理解了这一切。

对象原型定义的方法可以直接在对象上调用。例如,如果 obj 有一个原型,它有一个名为 'doSomething' 的方法,那么我们可以调用obj.doSomething().

于 2012-09-19T04:11:28.070 回答