|
| 1 | +/* |
| 2 | + * New ES6 Arrow Functions allows us to preserve the context of our callbacks |
| 3 | + * |
| 4 | + */ |
| 5 | + |
| 6 | + |
| 7 | +let object = { |
| 8 | + collection: ['PatrickJS', 'Lukas', 'Jeff', 'Dan'], |
| 9 | + value: 'print some value:', |
| 10 | + method: function() { |
| 11 | + console.log(this.value, 'method'); |
| 12 | + this.collection.forEach(function(item) { |
| 13 | + console.log(this.value, item); |
| 14 | + }); |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +// notice how this.value inside of the forEach callback is `undefined` |
| 19 | +object.method(); |
| 20 | + |
| 21 | + |
| 22 | +let object2 = { |
| 23 | + collection: ['PatrickJS', 'Lukas', 'Jeff', 'Dan'], |
| 24 | + value: 'print some value:', |
| 25 | + method: function() { |
| 26 | + console.log(this.value, 'method'); |
| 27 | + this.collection.forEach((item) => { |
| 28 | + console.log(this.value, item); |
| 29 | + }); |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +// we fixed this by preserving the context for the callback |
| 34 | +object2.method(); |
| 35 | + |
| 36 | +/* |
| 37 | + * what's happening is the context of when the function was created is preserved in the function |
| 38 | +
|
| 39 | +var object2 = { |
| 40 | + collection: ['PatrickJS', 'Lukas', 'Jeff', 'Dan'], |
| 41 | + value: 'print some value:', |
| 42 | + method: function() { |
| 43 | + var _self = this; |
| 44 | + console.log(this.value, 'method'); |
| 45 | + this.collection.forEach(function(item) { |
| 46 | + console.log(_self.value, item); |
| 47 | + }); |
| 48 | + } |
| 49 | +}; |
| 50 | +
|
| 51 | + * here's another way to write this in ES5 |
| 52 | +
|
| 53 | +var object2 = { |
| 54 | + collection: ['PatrickJS', 'Lukas', 'Jeff', 'Dan'], |
| 55 | + value: 'print some value:', |
| 56 | + method: function() { |
| 57 | + console.log(this.value, 'method'); |
| 58 | + this.collection.forEach(function(item) { |
| 59 | + console.log(this.value, item); |
| 60 | + }.bind(this)); |
| 61 | + } |
| 62 | +}; |
| 63 | + */ |
| 64 | + |
| 65 | + |
| 66 | +function callingBack(callback) { |
| 67 | + callback(); |
| 68 | +} |
| 69 | + |
| 70 | +console.log('arrow callback pattern'); |
| 71 | +try { |
| 72 | + |
| 73 | + callingBack(object2.method); // this doesn't work and throws an error |
| 74 | + |
| 75 | +} catch(e) { console.error(e); } |
| 76 | + |
| 77 | +// very common pattern in order to preserve the context |
| 78 | +callingBack(() => object2.method()); |
0 commit comments