Skip to content

Commit 0cb75f1

Browse files
committed
added 'about this'
1 parent 8ff1a11 commit 0cb75f1

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

jskoans.htm

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@
1919
<script type="text/javascript" src="topics/about_reflection.js"></script>
2020
<script type="text/javascript" src="topics/about_prototypal_inheritance.js"></script>
2121
<script type="text/javascript" src="topics/about_functions_and_closure.js"></script>
22+
<script type="text/javascript" src="topics/about_this.js"></script>
2223
<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>
2425

2526
</head>
2627
<body>

topics/about_this.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+

0 commit comments

Comments
 (0)