JavaScript provides many different ways for creating and using objects.
The following code shows how to create objects with an object's functions and properties.
We can also use the prototype to create objects.
When building the data structure we used the following way: create objects by defining a constructor function that includes declarations for an object's properties and functions, followed by definitions for the functions.
Here is the constructor function for an account object:
function Account(amount) { this.balance = amount; // property this.deposit = deposit; // function this.withdraw = withdraw; // function this.toString = toString; // function }
The this
keyword is used to link each function and property to an object instance.
The following code lists the function definitions for the preceding declarations:
function deposit(amount) { this.balance += amount; } function withdraw(amount) { if (amount <= this.balance) { this.balance -= amount; } if (amount > this.balance) { print("Insufficient funds"); } } function toString() { return "Balance: " + this.balance; }
We use the this
keyword with the balance property.
In this way the
interpreter knows which object's balance property we are referencing.
The following code is the complete definition for Account class.
function Account(amount) { //from w w w . java2 s .c om
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) {
print("Insufficient funds");
}
}
function toString() {
return "Balance: " + this.balance;
}
var account = new Account(50);
account.deposit(10);
console.log(account.toString());
account.withdraw(7);
console.log(account.toString());
account.withdraw(8);
console.log(account.toString());
The code above generates the following result.