JavaScript には、String、Date、Array などの組み込みオブジェクトがいくつかあります。
オブジェクトは、プロパティとメソッドを備えた特別な種類のデータです。
オブジェクトのプロパティにアクセスするための構文は次のとおりです。
objectName.propertyName
例:
var message="Hello World!";
var x=message.length;
上記のコードを実行した後の x の値は次のようになります: 12
message がオブジェクトであることに注意してください。
new を使用してオブジェクトをインスタンス化し、それにプロパティを追加する別の例を次に示します。
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
さて、ここにクラスの例があります:
function HelloWorld(hour)
{
// class "constructor" initializes this.hour field
if (hour)
{
// if the hour parameter has a value, store it as a class field
this.hour = hour;
}
else
{
// if the hour parameter doesn't exist, save the current hour
var date = new Date();
this.hour = date.getHours();
}
// display greeting
this.DisplayGreeting = function()
{
if (this.hour >= 22 || this.hour <= 5)
document.write("Goodnight, world!");
else
document.write("Hello, world!");
}
}
この例では、HelloWorld がクラスです。