File tree Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change 19
19
< script type ="text/javascript " src ="topics/about_reflection.js "> </ script >
20
20
< script type ="text/javascript " src ="topics/about_prototypal_inheritance.js "> </ script >
21
21
< script type ="text/javascript " src ="topics/about_functions_and_closure.js "> </ script >
22
+ < script type ="text/javascript " src ="topics/about_this.js "> </ script >
22
23
< script type ="text/javascript " src ="topics/about_scope.js "> </ script >
23
- < script type ="text/javascript " src ="topics/about_regular_expressions.js "> </ script >
24
+ < script type ="text/javascript " src ="topics/about_regular_expressions.js "> </ script >
24
25
25
26
</ head >
26
27
< body >
Original file line number Diff line number Diff line change
1
+ module ( "About this (topics/about_this.js)" ) ;
2
+
3
+ test ( "'this' inside a method" , function ( ) {
4
+ var person = {
5
+ name : 'bob' ,
6
+ intro : function ( ) {
7
+ return "Hello, my name is " + this . __ ;
8
+ }
9
+ }
10
+ equals ( person . intro ( ) , "Hello, my name is bob" ) ;
11
+ } ) ;
12
+
13
+ test ( "'this' on unattached function" , function ( ) {
14
+ var person = {
15
+ handle : 'bob' ,
16
+ intro : function ( ) {
17
+ return "Hello, my name is " + this . handle ;
18
+ }
19
+ }
20
+
21
+ var alias = person . intro ;
22
+
23
+ // if the function called as an object property 'this' is the global context
24
+ // (window in a browser)
25
+ window . __ = 'Peter' ;
26
+ equals ( "Hello, my name is Peter" , alias ( ) ) ;
27
+ } ) ;
28
+
29
+ test ( "'this' set explicitly" , function ( ) {
30
+ var person = {
31
+ handle : 'bob' ,
32
+ intro : function ( ) {
33
+ return "Hello, my name is " + this . handle ;
34
+ }
35
+ }
36
+
37
+ // calling a function with 'call' lets us assign 'this' explicitly
38
+ var message = person . intro . call ( { __ : "Frank" } ) ;
39
+ equals ( message , "Hello, my name is Frank" ) ;
40
+ } ) ;
41
+
42
+ // extra credit: underscore.js has a 'bind' function http://documentcloud.github.com/underscore/#bind
43
+ // read the source and see how it is implemented
44
+
You can’t perform that action at this time.
0 commit comments