Call, Apply function prototype methods (friendship relation)

JS
S
JavaScript

Basically it allows to call a method of an object from a different object (friendship relation). Call() will use CSV and Apply() will use [array].

1function sendTelemetry(){
2  console.log(`Sensor 1 measured ${this.value}`)
3}
4
5const device1 = {
6  type: 'reader',
7  value: 100
8}
9
10sendTelemetry.call(device1);
11sendTelemetry.apply(device1);
12
13// Examples
14// Slice
15const nrs = [1,2,3,4,5];
16const slice1 = nrs.slice.call(nrs,1,4); // call = arguments as csv
17const slice2 = nrs.slice.apply(nrs,[1,4]); // apply = arguments as array
18console.log(slice1);
19console.log(slice2);
20
21// Math.max
22let max = Math.max.apply(null, nrs); 
23console.log(max);
24max = Math.max.call(null, 1,2,3); 
25console.log(max);
26
27// 2 Functions
28function suffix(x){
29  return x + '</a>';
30}
31
32function prefix(x){
33    return '<a>' + x;
34}
35
36function dummy(){}
37
38const fullHref = prefix.call(dummy,'test');
39console.log(fullHref);
40
41// Classes Inheritance (friendship relation)
42function cls1(){
43  this.a = 7;
44  this.sendTelemetry = function(x){
45   const val = x+this.a; 
46    console.log(val)
47   return val;
48  }
49}
50
51function cls2(){
52  cls1.call(this);
53}
54
55const c2 = new cls2();
56c2.sendTelemetry(6);

Created on 12/5/2017