Hatena::Groupmnemonic

きおく屋めがねばし

 | 

2012-12-01

「3.6 ラッパーオブジェクト」

Wrapper Objects

JavaScript のオブジェクトは複合型の値です。つまり、プロパティ (名前付きの値) の集合体です。プロパティの値を参照するときは、「.」を使って表記します。プロパティが関数の場合は、メソッドと呼びます。オブジェクト o のメソッド m を呼び出すときは、o.m() と記述します。

JavaScript objects are composite values: they are a collection of properties or named values. We refer to the value of a property using the . notation. When the value of a property is a function, we call it a method. To invoke the method m of an object o, we write o.m().

We've also seen that strings have properties and methods:

var s = "hello world!";                              // A string
var word = s.substring(s.indexOf(" ")+1, s.length);  // Use string properties

Strings are not objects, though, so why do they have properties?

文字列と同じような理由で、数値や論理値もメソッドを持ちます。

There are not wrapper objects for the null and undefined values: any attempt to access a property of one of these values causes a TypeError.

Consider the following code and thinking about what happens when it is executed:

var s = "test";    // Start with a string value.
s.len = 4;         // Set a property on it.
var t = s.len;     // Now query the property

This code demonstrates that string, numbers, and boolean values behave like objects when you try to read the value of a property (or method) from them. But if you attempt to set the value of a property, that attempt is silently ignored: the change is made on a temporary object and does not persist.

このように、文字列や数値、論理値のプロパティにアクセスするときに生成される一時的なオブジェクトのことをラッパーオブジェクトと呼びます。

Note that it is possible (but almost never necessary or useful) to explicitly create wrapper objects,by invoking the String(),Number(), or Boolean() constructors:

var s = "test", n = 1, b = true;  // A string, number, and boolean values
var S = new String(s);            // A String object
var N = new Number(n);            // A Number object
var B = new Boolean(b);           // A Boolean object

JavaScript converts wrapper objects into the wrapped primitive value as necessary, so the objects S, N, and B above usually, but not always, behave just the values s, n, and b. The == equality operator treats a value and its wrapper object as equal,but you can distinguish them with the === strict equality operator. The typeof operator will also show you the difference between a primitive value and its wrapper object.


トラックバック - http://mnemonic.g.hatena.ne.jp/paragramma/20121201
 |