With Reflect.apply() we can control the context of 'this'
Code
Example One - Using reflect apply
//ES6 Reflect API - Calling functions with reflect.apply()
class Daughter {
constructor(name, age) {
this.name = name;
this.age = age;
}
dance() {
console.log(this.name + ', is dancing.')
}
}
let daughter = Reflect.construct(Daughter, ['Annabelle', 2.5]);
//Call the dance function method #1
// daughter.dance()
/**
* Using Reflect apply()
*
* @{function} the method to call
* @{this} what to apply this to
*/
Reflect.apply(daughter.dance, daughter, []);
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
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
Example Two - Using reflect apply - changing the context of 'this'
//ES6 Reflect API - Calling functions with reflect.apply()
class Daughter {
constructor(name, age) {
this.name = name;
this.age = age;
}
dance() {
console.log(this.name + ', is dancing.')
}
}
let daughter = Reflect.construct(Daughter, ['Annabelle', 2.5]);
//We are able to apply this context
Reflect.apply(daughter.dance, {}, []); // Undefined is dancing
Reflect.apply(daughter.dance, {name : 'Violet'}, []); // Violet is dancing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Example Three - Using reflect apply - passing arguments to inner method
//ES6 Reflect API - Calling functions with reflect.apply()
class Daughter {
constructor(name, age) {
this.name = name;
this.age = age;
}
dance(danceSpeed) {
console.log(this.name + ', is dancing ' + danceSpeed)
}
}
let daughter = Reflect.construct(Daughter, ['Annabelle', 2.5]);
Reflect.apply(daughter.dance, daughter, []); // Annabelle is dancing undefined
Reflect.apply(daughter.dance, daughter, ['quickly']); // Annabelle is dancing quickly
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23