Muestra las diferencias entre dos versiones de la página.
| Ambos lados, revisión anterior Revisión previa Próxima revisión | Revisión previa | ||
|
wiki2:js [2022/11/03 15:16] alfred [JavaScript Development Tools] |
wiki2:js [2022/11/03 16:21] (actual) |
||
|---|---|---|---|
| Línea 1105: | Línea 1105: | ||
| </code> | </code> | ||
| + | ==== Arrow functions ==== | ||
| + | This: | ||
| + | <code javascript> | ||
| + | const lordify = function(firstName) { | ||
| + | return `${firstName} of Canterbury`; | ||
| + | }; | ||
| + | </code> | ||
| + | Is the same than this: | ||
| + | <code javascript> | ||
| + | const lordify = firstName => `${firstName} of Canterbury`; | ||
| + | </code> | ||
| + | Arrow functions protect the scope of this. | ||
| + | For example this fails: | ||
| + | <code javascript> | ||
| + | const tahoe = { | ||
| + | mountains: ["Freel", "Rose", "Tallac", "Rubicon", "Silver"], | ||
| + | print: function(delay = 1000) { | ||
| + | console.log(this); // Window {} | ||
| + | setTimeout(function() { | ||
| + | console.log(this.mountains.join(", ")); | ||
| + | }, delay); | ||
| + | }}; | ||
| + | tahoe.print(); // Uncaught TypeError: Cannot read property 'join' of undefined | ||
| + | </code> | ||
| + | But this not: | ||
| + | <code javascript> | ||
| + | const tahoe = { | ||
| + | mountains: ["Freel", "Rose", "Tallac", "Rubicon", "Silver"], | ||
| + | print: function(delay = 1000) { | ||
| + | setTimeout(() => { | ||
| + | console.log(this.mountains.join(", ")); | ||
| + | }, delay); | ||
| + | } | ||
| + | }; | ||
| + | tahoe.print(); // Freel, Rose, Tallac, Rubicon, Silver | ||
| + | </code> | ||