Académique Documents
Professionnel Documents
Culture Documents
JavaScript Tutorial
Home Tutorial JavaScript: from the Ground to Closures Mastering data types
Number, Math Array Tutorial
Objects
Ilya Kantor
1. Creating objects 1. Literal syntax 2. Non-existing properties, u n d e f i n e d 3. Checking if a key exists 4. Iterating over keys-values 1. Order of iteration 5. Object variables are references 6. Properties and methods 1. Calling methods 7. The constructor function, new 1. A simple example 2. An example with the method 8. Built-in Objects 1. String, Number, Boolean 9. Summary Objects in JavaScript are kind of two-faced.
Like
14
Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators
Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff
From one side, an object is an associative array (called hash in some languages). It stores key-value pairs. From the other side, objects are used for object-oriented programming, and thats a different story. In this section we start from the first side and then go on to the second one.
Creating objects
An empty object (you may also read as empty associative array) is created with one of two syntaxes: 1 .o=n e wO b j e c t ( ) 2 .o={} / /t h es a m e It stores any values by key which you can assign or delete using dot notation:
Run!
0 1 0 2 0 3 0 4 0 5 0 6
v a ro b j={ }
/ /c r e a t ee m p t yo b j e c t( a s s o c i a t i v ea r r a y )
o b j . n a m e=' J o h n ' / /a d de n t r yw i t hk e y' n a m e 'a n dv a l u e' J o h n ' / /N o wy o uh a v ea na s s o c i a t i v ea r r a yw i t hs i n g l ee l e m e n t / /k e y : ' n a m e ' ,v a l u e :' J o h n '
0 7 0 8 a l e r t ( o b j . n a m e )/ /g e tv a l u eb yk e y' n a m e ' 0 9 1 0 d e l e t eo b j . n a m e/ /d e l e t ev a l u eb yk e y' n a m e ' 1 1 1 2 / /N o ww eh a v ea ne m p t yo b j e c to n c ea g a i n You can use square brackets instead of dot. The key is passed as a string:
Run!
1 2 3 4 5 6 7
Theres a significant difference between dot and square brackets. o b j . p r o preturns the key named prop o b j [ p r o p ]returns the key named by value of prop: 1 v a rp r o p=' n a m e ' 2 3 / /r e t u r n ss a m ea so b j [ ' n a m e ' ] ,w h i c hi ss a m ea so b j . n a m e 4 a l e r t ( o b j [ p r o p ] )
http://javascript.info/tutorial/objects
1/8
1/21/2014
Literal syntax
You can also set values of multiple properties when creating an object, using a curly-bracketed list: { k e y 1 : v a l u e 1 ,k e y 2 :v a l u e 2 ,. . .} . Heres an example.
Literal syntax is a more readable alternative to multiple assignments: 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 v a rm e n u S e t u p={ w i d t h : 3 0 0 , h e i g h t :2 0 0 , t i t l e :" M e n u " } / /s a m ea s : v a rm e n u S e t u p={ } m e n u S e t u p . w i d t h=3 0 0 m e n u S e t u p . h e i g h t=2 0 0 m e n u S e t u p . t i t l e=' M e n u '
1. Create an empty object u s e r . 2. Add a property n a m ewith value J o h n . 3. Change value of n a m eto S e r g e . 4. Remove property n a m efrom the object.
Open solution
It is also possible to create nested objects: 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 v a ru s e r={ n a m e : " R o s e " , a g e :2 5 , s i z e :{ t o p :9 0 , m i d d l e :6 0 , b o t t o m :9 0 } } a l e r t (u s e r . n a m e)/ /" R o s e " a l e r t (u s e r . s i z e . t o p)/ /9 0
Non-existing properties, u n d e f i n e d
We can try to get any property from an object. There will be no error. But if the property does not exist, then u n d e f i n e dis returned:
Run!
1 v a ro b j={ } 2 3 v a rv a l u e=o b j . n o n e x i s t a n t 4
http://javascript.info/tutorial/objects
2/8
1/21/2014
5 a l e r t ( v a l u e )
So its easy to check whether a key exists in the object, just compare it against u n d e f i n e d : i f( o b j . n a m e! = =u n d e f i n e d ){/ /s t r i c t ( ! )c o m p a r i s o n a l e r t ( "I ' v eg o tan a m e !" ) }
1 v a ro b j={k e y :u n d e f i n e d} 2 3 a l e r t (o b j . k e y)/ /u n d e f i n e d . .j u s ti ft h e r ew e r en ok e y Hopefully, there is a special " i n "operator to check for keys. Its syntax is " p r o p "i no b j , like this:
Run!
1 v a ro b j={k e y :u n d e f i n e d} 2 3 a l e r t ( " k e y "i no b j )/ /t r u e ,k e ye x i s t s 4 a l e r t ( " b l a b l a "i no b j )/ /f a l s e ,n os u c hk e y In real life, usually n u l lis used a no-value, leaving u n d e f i n e dfor something truly undefined.
0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1
Order of iteration
In theory, the order of iteration over object properties is not guaranteed. In practice, there is a de-facto standard about it. IE<9, Firefox, Safari always iterate in the order of definition. Opera, IE9, Chrome iterate in the order of definition for string keys. Numeric keys become sorted and go before string keys. Try the code below in different browsers.
Run!
0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2
v a ro b j={ " n a m e " :" J o h n " , " 1 " :1 , a g e :2 5 , " 0 " :0 } o b j [ 2 ]=2/ /a d dn e wn u m e r i c o b j . s u r n a m e=' S m i t h '/ /a d dn e ws t r i n g f o r ( v a rk e yi no b j )a l e r t ( k e y ) / /0 ,1 ,2 ,n a m e ,a g e ,s u r n a m e < -i nO p e r a ,I E 9 ,C h r o m e / /n a m e ,1 ,a g e ,0 ,2 ,s u r n a m e < -i nI E < 9 ,F i r e f o x ,S a f a r i
Here numeric keys are those which can be parsed as integers, so " 1 "is a numeric key. There is an issue about it in Chrome, with long discussion at http://code.google.com/p/v8/issues/detail? id=164.
1/21/2014
1 v a rc o u n t r i e s={ 2 / /e v e r yo p t i o ni sg i v e na s" i d " :" t i t l e " 3 " 5 " :" A f g h a n i s t a n " , 4 " 3 " :" B r u n e i " , 5 " 8 " :" I t a l y " 6 } And now we need to build S E L E C Twith these options in same order. But Chrome wont let us, it will resort numeric keys. An ugly, but working hack is to prepend numeric keys by an underscore ' _ ' . When browser reads such object, it removes the underscore:
Run!
1 2 3 4 5 6 7 8 9
v a rc o u n t r i e s={ / /_ i d :t i t l e " _ 5 " :" A f g h a n i s t a n " , " _ 3 " :" B r u n e i " , " _ 8 " :" I t a l y " } f o r ( v a rk e yi nc o u n t r i e s ){ a l e r t ( k e y . s u b s t r ( 1 ) )/ /k e e p st h eo r d e ra l w a y s }
1 2 3 4 5 6 7
o b j . n a m e=' P e t e r ' ;/ /c h a n g ed a t ai nt h eo b j e c t
a l e r t ( u s e r . n a m e ) ; / /n o wP e t e r
Same happens when you pass an object to function. The variable is a reference, not a value. Compare this:
Run!
1 2 3 4 5 6 7 8
f u n c t i o ni n c r e m e n t ( v a l ){ v a l + + } v a l=5 i n c r e m e n t ( v a l ) a l e r t ( v a l )/ /v a li ss t i l l5
1 2 3 4 5 6 7 8
v a ro b j={v a l :5 } f u n c t i o ni n c r e m e n t ( o b j ){ o b j . v a l + + } i n c r e m e n t ( o b j ) a l e r t ( o b j . v a l )/ /o b j . v a li sn o w6
The difference is because in first example variable v a lis changed, while in second example o b jis not changed, but data which it references is modified instead.
Create a function m u l t i p l y N u m e r i cwhich gets an object and multiplies all numeric properties by 2. It should work like this: 0 1 / /b e f o r ec a l l 0 2 v a rm e n u={ 0 3 w i d t h :" 2 0 0 " , 0 4 h e i g h t :" 3 0 0 " ,
http://javascript.info/tutorial/objects
4/8
1/21/2014
0 5 t i t l e :" M ym e n u " 0 6 } 0 7 0 8 m u l t i p l y N u m e r i c ( m e n u ) 0 9 1 0 / /a f t e rc a l l 1 1 m e n u={ 1 2 w i d t h :4 0 0 , 1 3 h e i g h t :6 0 0 , 1 4 t i t l e :" M ym e n u " 1 5 } P.S. The function to check for numericality:
f u n c t i o ni s N u m e r i c ( n ){ r e t u r n! i s N a N ( p a r s e F l o a t ( n ) )& &i s F i n i t e ( n ) }
Open solution
Calling methods
When you put a function into an object, you can call it as method:
Run!
0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2
Note the t h i skeyword inside a s k N a m eand s a y H i . When a function is called from the object, t h i sbecomes a reference to this object.
Create an object named s u m m a t o rwith two methods: s u m ( a , b )returns a sum of two values r u n ( )prompts the visitor for two values and outputs their sum. As the result, s u m m a t o r . r u n ( )should prompt for two values and alert their sum. You can see it here in action: tutorial/intro/object/summator2.html
Open solution
http://javascript.info/tutorial/objects 5/8
1/21/2014
Create an object l a d d e rwith chainable calls. The source: 0 1 v a rl a d d e r={ 0 2 s t e p :0 , 0 3 u p :f u n c t i o n ( ){ 0 4 t h i s . s t e p + + 0 5 } , 0 6 d o w n :f u n c t i o n ( ){ 0 7 t h i s . s t e p 0 8 } , 0 9 s h o w S t e p :f u n c t i o n ( ){ 1 0 a l e r t ( t h i s . s t e p ) 1 1 } 1 2 } Currently it works in a dull way: 1 2 3 4 l a d d e r . u p ( ) l a d d e r . u p ( ) l a d d e r . d o w n ( ) l a d d e r . s h o w S t e p ( )/ /1
Open solution
A simple example
Run!
1 2 3 4 5 6 7 8
A function takes the following steps: 1. Create t h i s={ } . 2. The function then runs and may change t h i s , add properties, methods etc. 3. The resulting t h i sis returned. So, the function constructs an object by modifying t h i s . The result in the example above: 1 a n i m a l={ 2 n a m e :" b e a s t i e " , 3 c a n W a l k :t r u e 4 }
Traditionally, all functions which are meant to create objects with n e whave uppercased first letter in the name.
http://javascript.info/tutorial/objects
6/8
1/21/2014
By the way, a call without arguments may omit braces: v a ra n i m a l=n e wA n i m a l ( ) / /s a m ea s v a ra n i m a l=n e wA n i m a l In both cases a n i m a l . n a m ewill be u n d e f i n e d .
0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 1 3
Create an constructor function S u m m a t o rwhich creates an object with two methods: s u m ( a , b )returns a sum of two values r u n ( )prompts the visitor for two values and outputs their sum. n e wS u m m a t o r ( ) . r u n ( )should prompt for two values and alert their sum. You can see it here in action: tutorial/intro/object/summator2New.html
Open solution
Built-in Objects
The standard library of JavaScript includes a list of built-in objects. For example: Math Date RegExp provides methods for mathematical computations, - for dates, - for regular expressions. . Well meet their advanced usage further in the
1 a l e r t (" s t r i n g " . l e n g t h) 2 a l e r t (" l a l a " . t o U p p e r C a s e ( )) It works, because the interpreter converts a primitive to object, calls its method, and the returned value is primitive again. Same with numbers:
Run!
http://javascript.info/tutorial/objects
7/8
1/21/2014
Summary
Objects are associative arrays with additional features. Assign keys with o b j [ k e y ]=v a l u eor o b j . n a m e=v a l u e Remove keys with d e l e t eo b j . n a m e Iterate over keys with f o r ( k e yi no b j ) , remember iteration order for string keys is always in definition order, for numeric keys it may change. Properties, which are functions, can be called as o b j . m e t h o d ( ) . They can refer to the object as t h i s . Properties can be assigned and removed any time. A function can create new objects when run in constructor mode as n e wF u n c ( p a r a m s ) . It takes t h i s , which is initially an empty object, and assigns properties to it. The result is returned (unless the function has explicit r e t u r na n o t h e r O b j e c tcall). Names of such functions are usually capitalized. Number, Math Array
See also:
Wrong order in Object properties interation
The content of this site is available under the terms of CC BY-NC-SA. Ilya Kantor, 2011.
"JavaScript is a registered trademark of Oracle corp. This site is not affiliated with Oracle corp.
http://javascript.info/tutorial/objects
8/8