Vous êtes sur la page 1sur 8

1/21/2014

Objects | JavaScript Tutorial


Log in

JavaScript Tutorial
Home Tutorial JavaScript: from the Ground to Closures Mastering data types
Number, Math Array Tutorial

JavaScript: from the Ground to Closures


JavaScript: from the Ground to Closures Javascript and related technologies First Steps Functions: declarations and expressions Mastering data types
Mastering data types String Number, Math Objects Array Conversion, toString and valueOf

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!

Donate Donate to this project

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

v a ro b j={ } o b j [ ' n a m e ' ]=' J o h n ' a l e r t ( o b j [ ' n a m e ' ] ) d e l e t eo b j [ ' n a m e ' ]

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

Objects | JavaScript Tutorial

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

Getting an object dump in Firefox


For debugging purposes, it is possible to get an object dump by calling toSource method, supported only in Firefox.
Run!

1 v a ru s e r={ 2 n a m e : " R o s e " , 3 s i z e :{ 4 t o p :9 0 , 5 m i d d l e :6 0 6 } 7 } 8 9 a l e r t (u s e r . t o S o u r c e ( ))/ /w o r k so n l yi nF i r e f o x

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 )

Objects | JavaScript Tutorial

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 !" ) }

Checking if a key exists


A peculiar coder (I bet you are) might have a question. What if I assign a key to u n d e f i n e dexplicitly? How to check if whether the object got such key?
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 (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.

Iterating over keys-values


There is a special f o r . . i nsyntax to list object properties: f o r ( k e yi no b j ){ . . .o b j [ k e y ]. . . } The following example demonstrates it.
Run!

0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1

v a rm e n u={ 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 " } ; f o r ( v a rk e yi nm e n u ){ v a rv a l=m e n u [ k e y ] ; } a l e r t ( " K e y :" + k e y + "v a l u e : " + v a l ) ;

Note how it is possible to define a variable right inside f o rloop.

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.

Force iteration order over numeric keys


http://javascript.info/tutorial/objects 3/8

1/21/2014

Objects | JavaScript Tutorial


Sometimes, we want f o r . . i nto keep the iteration order for numeric keys across all browsers. For example, server may generate a JavaScript object with select options, something like:
Run!

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 }

Now all browsers keep the order.

Object variables are references


A variable which is assigned to object actually keeps reference to it. That is, a variable stores kind-of pointer to real data. You can use the variable to change this data, this will affect all other references.
Run!

1 2 3 4 5 6 7

v a ru s e r={n a m e :' J o h n '} ;/ /u s e ri sr e f e r e n c et ot h eo b j e c t v a ro b j=u s e r ; / /o b jr e f e r e n c e ss a m eo b j e c t

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

And this (now changing val in object):


Run!

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:

Objects | JavaScript Tutorial

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

Properties and methods


You can store anything in object. Not just simple values, but also functions. 1 v a ru s e r={ 2 n a m e :" G u e s t " , 3 a s k N a m e :f u n c t i o n ( ){ 4 t h i s . n a m e=p r o m p t ( " Y o u rn a m e ? " ) 5 } , 6 s a y H i :f u n c t i o n ( ){ 7 a l e r t ( ' H i ,m yn a m ei s' + t h i s . n a m e ) 8 } 9 }

To check if a method is supported, we usually check its existance by i f : i f( u s e r . a s k N a m e )u s e r . a s k N a m e ( )

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

v a ru s e r={ n a m e :" G u e s t " , a s k N a m e :f u n c t i o n ( ){ t h i s . n a m e=p r o m p t ( " Y o u rn a m e ? " ) } , s a y H i :f u n c t i o n ( ){ a l e r t ( ' H i ,m yn a m ei s' + t h i s . n a m e ) } } u s e r . a s k N a m e ( ) u s e r . s a y H i ( )

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

Objects | JavaScript Tutorial

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

Modify the code, so the methods can be chained like this: l a d d e r . u p ( ) . u p ( ) . d o w n ( ) . u p ( ) . d o w n ( ) . s h o w S t e p ( ) / /1

Open solution

The constructor function, new


An object can be created literally, using o b j={. . . }syntax. Another way of creating an object in JavaScript is to construct it by calling a function with n e wdirective.

A simple example
Run!

1 2 3 4 5 6 7 8

f u n c t i o nA n i m a l ( n a m e ){ t h i s . n a m e=n a m e t h i s . c a n W a l k=t r u e } v a ra n i m a l=n e wA n i m a l ( " b e a s t i e " ) a l e r t ( a n i m a l . n a m e )

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 }

If the function returns an object, `this` is ignored


This feature is rarely used, but still interesting to know:
Run!

1 f u n c t i o nA n i m a l ( ){ 2 t h i s . n a m e=' M o u s i e ' 3 r e t u r n{n a m e :' G o d z i l l a '} / /< -w i l lb er e t u r n e d 4 } 5 6 a l e r t (n e wA n i m a l ( ) . n a m e) / /G o d z i l l a

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

Objects | JavaScript Tutorial

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 .

An example with the method


Lets declare a function U s e rand create two objects with s a y H imethod.
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 1 3

f u n c t i o nU s e r ( n a m e ){ t h i s . n a m e=n a m e t h i s . s a y H i=f u n c t i o n ( ){ a l e r t ( "Ia m" + t h i s . n a m e ) } ;

v a rj o h n=n e wU s e r ( " J o h n " ) v a rp e t e r=n e wU s e r ( " P e t e r " ) j o h n . s a y H i ( ) p e t e r . s a y H i ( )

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

Functions are also objects, instances of the new Function book.

String, Number, Boolean


The three objects are standing apart from the others. These are S t r i n g ,N u m b e r ,B o o l e a n . Unlike other objects, they are never created explicitly. No one should ever make a n e wS t r i n g . Primitives should be used instead. The purpose of these objects is to support methods, which can be called directly on a primitive, like this:
Run!

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!

1 a l e r t (1 2 3 . 4 5 6 . t o F i x e d ( 2 )) 2 3 a l e r t (1 2 3 . . t o F i x e d ( 2 ))/ /T w od o t si sn o tat y p o . 4 / /1 2 3 . t o F i x e d ( 2 )w o n ' tw o r k ,b e c a u s et h ee x p e c t st h ed e c i m a lp a r ta f t e r' . '

http://javascript.info/tutorial/objects

7/8

1/21/2014

Objects | JavaScript Tutorial

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

Vous aimerez peut-être aussi