Can I use arrow functions in objects? Or they need to use the usual? Not quite understand it from the documentation. And yes, if you can, an example.
- What is meant by using arrow functions in objects ? - Grundy
- @Grundy I mean arrow functions from the new standard, as I understand in the objects it makes no sense to use them because this for this window is J.Joe
- objects are different. Give an example of using the switch function in the object - Grundy
2 answers
Arrow functions are bound to the value of this . So everything is as usual. But they are anonymous, so the method will not work if you are talking about it.
You can, but it should be borne in mind that the switch functions do not have their own this , that is, the following calls will work in different ways:
const name = 'Alisa'; const obj = { name: 'John', getArrowName: () => `Hello, ${this.name}`, getName: function() { return `Hello, ${this.name}`; }; }; obj.getArrowName(); //"Hello, Alisa" obj.getName(); //"Hello, John" getName() works as getName() . And when you call getArrowName() , this will refer not to obj , but to the surrounding lexical environment.
It is very convenient to use them for callback functions:
const options = { success: (response) => response, error: (xhr) =>throw new Error(xhr.status), }; $.ajax(options); Also, you may be interested in an interesting “short writing of methods” ( It's shorthand method names ), which, like the arrow functions, appeared in ES6, and which is no different in meaning from the usual methods.
var o = { property([parameters]) {}, }; // первый пример можно переписать так: const obj = { name: 'John', getName() { return `Hello, ${this.name}`; }; }; - I meant that for an object method they (arrow functions) are not suitable because obj.getArrowName (); will issue "Hello, undefined" - J.Joe
- I gave an example below how convenient it is to use the arrow functions in objects - callbacks. Still, if you met with the construct
var self = thisorvar that = this, then you can simply get rid of them using the arrow functions. So you can use it only in necessary cases :) - saaaaaaaaasha - @saaaaaaaaasha thank you very much for the answer catch the plus sign - Demon __ ANT