Content deleted Content added
→JavaScript: copy editing |
→JavaScript: copy editing (wikEd on to diagnose dash usage) |
||
Line 599:
====Object====
An object is similar to a map—both let you set keys to values, retrieve those values, delete keys, and detect whether
However, there are important differences that make a map preferable in certain cases. In JavaScript an object is a mapping from property names to values—that is, an associative array with one caveat: the keys of an object must be either a string or a symbol (native objects and primitives implicitly converted to a string keys are allowed). Objects also include one feature unrelated to associative arrays: an object has a prototype, so it contains default keys that could
▲An object is similar to a map—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), objects have been used as maps historically.
▲However, there are important differences that make a map preferable in certain cases. In JavaScript an object is a mapping from property names to values—that is, an associative array with one caveat: the keys of an object must be either a string or a symbol (native objects and primitives implicitly converted to a string keys are allowed). Objects also include one feature unrelated to associative arrays: an object has a prototype, so it contains default keys that could collide with your own keys if you're not careful. So doing a lookup for a property will forward the lookup to the prototype if the object does not define the property itself.
An object literal is written as <code>{ property1 : value1, property2 : value2, ... }</code>. For example:
Line 614 ⟶ 613:
</syntaxhighlight>
To prevent the lookup
<syntaxhighlight lang=JavaScript>
Object.setPrototypeOf(myObject, null);
</syntaxhighlight>
As of ECMAScript 5 (ES5),
<syntaxhighlight lang=JavaScript>
Line 637:
</syntaxhighlight>
Lookup is written using property
<syntaxhighlight lang=JavaScript>
Line 675:
</syntaxhighlight>
In modern JavaScript it's considered bad form to use the Array type as an associative array. Consensus is that the Object type and Map/WeakMap classes are best for this purpose. The reasoning behind this is that if Array is extended via prototype and Object is kept pristine, 'for(in)' loops will work as expected on associative 'arrays'. This issue has been
See [http://blog.metawrap.com/2006/05/30/june-6th-is-javascript-array-and-object-prototype-awareness-day/ JavaScript Array And Object Prototype Awareness Day] for more information on the issue.
|