this关键字在函数中的应用

this 关键字用来将方法和属性绑定到一个对象的实例上

<script type="text/javascript">
    /*  检查银行账户对象的构造函数*/
    function Checking(amount) {
        this.balance = amount; // 属性
        this.deposit = deposit; // 方法
        this.withdraw = withdraw; // 方法
        this.toString = toString; // 方法
    }
    function deposit(amount) {
        this.balance += amount;
    }
    function withdraw(amount) {
        if (amount <= this.balance) {
            this.balance -= amount;
        }
        if (amount > this.balance) {
            alert("Insufficient funds");
        }
    }
    function toString() {
        return "Balance: " + this.balance;
    }
    var account = new Checking(500);
    account.deposit(1000);
    alert(account.toString()); //Balance: 1500
    account.withdraw(750);
    alert(account.toString()); // 余额: 750
    account.withdraw(800); // 显示 " 余额不足 "
    alert(account.toString()); // 余额: 750
</script>
原文地址:https://www.cnblogs.com/feile/p/5369598.html