Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1138 How can I create a Money object?

irt.org | Knowledge Base | JavaScript | Object | Q1138 [ previous next ]

Q1138 How can I create a Money object?

JavaScript, unlike Java or C or C++, is an untyped language, in other words instead of doing:

int x = 3;
string y = "Hello world";

In JavaScript you do:

var x = 3;
var y = "Hello world";

The variable type is implied when the value is defined.

There are four basic variable types in JavaScript: String, Number, Boolean and Object

There are many inbuilt objects, for example: Date, Form, Function, Window.

You can create your own objects, with their own properties and methods.

We could create our own Money object:

<script language="JavaScript"><!--
// Define the constructor for the Money object:

function Money (currency,value) {
    this.currency = currency;
    this.value = value;
    this.text = currency + value;

    this.equatesTo = Money_equatesTo;
}

// Create Money object Constants:

// exchange rate US Dollar to UK Pound
Money.prototype.UKPtoUSD = 1.59;
// exchange rate UK Pound to US Dollar
Money.prototype.USDtoUKP = 0.63;

// Create Money object methods:

function Money_equatesTo() {
    if (this.currency == '$')
        alert(this.text + ' = £' + Math.round((this.value * this.USDtoUKP)*100)/100);
    else
        alert(this.text + ' = $' + Math.round((this.value * this.UKPtoUSD)*100)/100); 
}

// Create instances of the Money object:

var money1 = new Money('$',19.99);
var money2 = new Money('£',25.75);

// Use the Money object methods:

money1.equatesTo();
money2.equatesTo();
//--></script>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.