Visit Mozilla.org

Dokumentacja języka JavaScript 1.5:Operatory:Operatory pamięci

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...

Spis treści

[edytuj] Podsumowanie

Operatory pamięci zapewniają dostęp do własności lub metod obiektu.

An object is actually an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of properties and methods (properties that refer to functions). There are two ways to access these properties: dot notation and bracket notation (a.k.a. subscript operator).

Uwaga: the ECMAScript specification labels these operators as "property accessors" rather than "member operators".

[edytuj] Dot notation

get = object.property;
object.property = set;

property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

Example:

document.createElement('pre');

Here, the method named "createElement" is retrieved from document and is called.

[edytuj] Bracket notation

get = object[property_name];
object[property_name] = set;

property_name is a string. The string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

Example:

document['createElement']('pre');

This does the exact same thing as the previous example.

[edytuj] Nazwy własności

Nazwy własności muszą być łańcuchami. This means that non-string objects cannot be used as keys in the object. Dowolny obiekt nie będący łańcuchem, wliczając w to liczby, zostanie zrzutowany do obiektu string poprzez metodę toString.

Przykłady:

var object = {};
object['1'] = 'value';
alert(object[1]);

This outputs "value", since 1 is typecasted into '1'.

var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'value';
alert(object[bar]);

This also outputs "value", since both foo and bar are converted to the same string. In the SpiderMonkey JavaScript engine, this string would be "[object Object]".

[edytuj] Wiązanie metod

A method is not bound to the object that it is a method of. Specifically, this is not fixed in a method, i.e. this does not necessarily refer to an object containing the method. this is instead "passed" by the function call.

Zobacz także Wiązanie metod.

[edytuj] Note on eval

JavaScript novices often make the mistake of using eval where the bracket notation can be used instead. For example, the following syntax is often seen in many scripts.

x = eval('document.form_name.' + strFormControl + '.value');

eval is slow and should be avoided whenever possible. It is better to use the bracket notation instead:

x = document.form_name[strFormControl].value;