[JavaScript] Static Data

Using constructor functions, you can mimic classes in JavaScript. How about static members? Can we create them in JavaScript?

 

1. Class

Let’s create a simple class function.

function Account(p) {
  this.principal = p;
}
Account.prototype.getBalanceWithInterest = function () {
  return (this.principal * (1 + 0.1)).toFixed(2);
}

var acc = new Account(100);

alert(acc.getBalanceWithInterest()); // 110

 

2. Static Data

What if you want to have the interest rate as a static variable? You can use the dynamic nature of JavaScript object.

function Account(p) {
  this.principal = p;
}

Account.InterestRate = 0.1; // works like a static member

Account.prototype.getBalanceWithInterest = function () {
  return (this.principal * (1 + Account.InterestRate)).toFixed(2);
}

var acc = new Account(100);

alert(Account.InterestRate); // 0.1
alert(acc.InterestRate); // undefined
alert(acc.getBalanceWithInterest()); // 110

Note that you can access “InterestRate” only through the constructor name.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s