Repository navigation
Expand file tree
/
Copy paththis-scope.js
More file actions
57 lines (45 loc) · 1.43 KB
/
Copy paththis-scope.js
File metadata and controls
57 lines (45 loc) · 1.43 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Fruit{
constructor(type, color){
this.getType = function(){return type};
this.getColor = () => color;
}
}
const apple = new Fruit("Apple", "Red");
// Fruit.prototype.message = () => `I am a ${this.getColor()} ${this.getType()}`;
// console.log(apple.message());
/**
Uncaught TypeError: this.getColor is not a function
at Fruit.message (<anonymous>:10:48)
at <anonymous>:12:19
**/
Fruit.prototype.message = function() {
return `I am a ${this.getColor()} ${this.getType()}`;
};
console.log(apple.message());
/**
I am a Red Apple
**/
const orange = new Fruit("Orange", "Orange");
let fruitMessage = apple.message;
console.log(fruitMessage);
// [Function]
console.log(fruitMessage.call(orange));
// I am a Orange Orange
console.log(fruitMessage.apply(orange));
// I am a Orange Orange
// console.log(fruitMessage());
/** TypeError: this.getColor is not a function
`this` is evaluated when the code is run rather than when
the object is created. By calling fruitMessage() in this way,
you have taken apple.message out of apple's scope and moved it
into the global scope. `this.getColor()` is now looking for `getColor()`
in the global scope which is undefined.
**/
fruitMessage = apple.message.bind(orange);
/** bind doesn't execute the function
it hold onto it and will apply the `this` scope when you call it later
**/
console.log(fruitMessage);
// [Function]
console.log(fruitMessage());
// I am a Orange Orange!