-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcall.js
More file actions
59 lines (48 loc) · 1.45 KB
/
call.js
File metadata and controls
59 lines (48 loc) · 1.45 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
58
59
// ======= CALL =======
const person = {
firstName: "Igor",
surName: "Petrenko",
middle: 'Andriiovych'
};
function getFullName(a, b) {
console.log(`That is ${this[a]} ${this[b]}`)
}
getFullName.call(person); // will print 'That is undefined undefined'
getFullName.call(person, 'firstName', 'surName');
getFullName.call(person, 'firstName', 'middle');
// ==== Method borrowing =====
function getArgs() {
// copying array's built-in method 'join' into arguments and naming it 'iJoin':
arguments.iJoin = [].join;
// calling the just copied 'iJoin' in the context of 'arguments':
const args = arguments.iJoin(' : ');
console.log(args);
}
getArgs(1, 4, 7, 'fuck', true);
// ====== How 'join' looks inside =======
// function myJoin(separator) {
// if (!this.length) return '';
// let str = this[0];
// for (let i=1; i<this.length; i++) {
// str = str + separator + this[i];
// }
// return str;
// }
// As 'this' even an object will do:
const user = {
0: 'Chris',
1: 'Nicholson',
2: 57,
length: 3
};
user.myjoin = [].join;
console.log(user.myjoin(' - ')); // prints 'Chris - Nicholson - 57'
// Copying [].join as above is not safe and not recommended
// instead you can call the join with 'call':
function logArgs() {
const newJoin = [].join;
const args = newJoin.call(arguments, '/');
console.log(args);
}
// Here we're calling join without copying, it's clear and safe:
logArgs(2, -6, 'shit', false); // prints '2/-6/shit/false'