forked from liammclennan/JavaScript-Koans
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabout_this.js
More file actions
44 lines (36 loc) · 1.32 KB
/
about_this.js
File metadata and controls
44 lines (36 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
module("About this (topics/about_this.js)");
test("'this' inside a method", function () {
var person = {
name: 'bob',
intro: function () {
return "Hello, my name is " + this.__;
}
}
equal(person.intro(), "Hello, my name is bob", "If an object has a method can you access properties inside it?");
});
test("'this' on unattached function", function () {
var person = {
globalName: 'bob',
intro: function () {
return "Hello, my name is " + this.globalName;
}
}
var alias = person.intro;
// if the function is not called as an object property 'this' is the global context
// (window in a browser). This is an example. Please do not do this in practise.
window.__ = 'Peter';
equal(alias(), "Hello, my name is Peter", "What does 'this' referer to when it is not part of an object?");
});
test("'this' set explicitly", function () {
var person = {
name: 'bob',
intro: function () {
return "Hello, my name is " + this.name;
}
}
// calling a function with 'call' lets us assign 'this' explicitly
var message = person.intro.call({__: "Frank"});
equal(message, "Hello, my name is Frank", "What does 'this' referer to when you use the 'call()' method?");
});
// extra credit: underscore.js has a 'bind' function http://documentcloud.github.com/underscore/#bind
// read the source and see how it is implemented