Przewodnik po języku JavaScript 1.5:Tworzenie nowych obiektów:Używanie inicjacji obiektu
z Mozilla Developer Center, polskiego centrum programistów Mozilli.
UWAGA: Tłumaczenie tej strony nie zostało zakończone.
Może być ona niekompletna lub wymagać korekty.
Chcesz pomóc? | Dokończ tłumaczenie | Sprawdź ortografię | Więcej takich stron...
[edytuj] Zastosowanie inicjacji obiektu
Uzupełnieniem możliwości tworzenia obiektów poprzez konstruktora funkcji, jest inicjator obiektów. Używanie inicjatora obiektów jest czasami wiązane z tworzeniem obiektów poprzez oznaczanie literowe. "Inicjator obiektu" jest nazwą zaczerpniętą ze standardów języka C++.
Składnia tworząca obiekt, używając inicjatora obiektu jest następująca:
objectName = {własnosc1:wartosc2, własnosc2:wartosc2,..., własnoscN:wartoscN}
gdzie objectName jest nazwą obiektu, each property I is an identifier (either a name, a number, or a string literal), and each value I is an expression whose value is assigned to the propertyI. The objectName and assignment is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable.
If an object is created with an object initializer in a top-level script, JavaScript interprets the object each time it evaluates the expression containing the object literal. In addition, an initializer used in a function is created each time the function is called.
The following statement creates an object and assigns it to the variable x if and only if the expression cond is true.
if (cond) x = {hi:"there"}
The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.
myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}}
You can also use object initializers to create arrays. Zobacz literałów tablicy.
JavaScript 1.1 and earlier. You cannot use object initializers. You can create objects only using their constructor functions or using a function supplied by some other object for that purpose. See Zastosowanie konstruktorów funkcji.