Sobes.tech
Junior — Middle

Kuidas erineb noolefunktsioonide kasutamine standardfunktsioonidest JavaScriptis?

sobes.tech AI

Vastus AI-lt

Arrow functions in JavaScript differ from standard functions in several key aspects:

  • this context: In arrow functions, this is lexically inherited from the surrounding context, meaning it does not create its own this context. In regular functions, this depends on how the function is called.

  • Absence of arguments: Arrow functions do not have their own arguments object. To access arguments, parameters or external variables should be used.

  • Cannot be used as constructors: Arrow functions cannot be invoked with new because they do not have an internal [[Construct]] method.

  • Shorter syntax: Arrow functions are generally shorter and more convenient for writing short functions.

Example:

const obj = {
  value: 10,
  regularFunc: function() {
    console.log(this.value); // 10
  },
  arrowFunc: () => {
    console.log(this.value); // undefined or value from external context
  }
};

obj.regularFunc(); // outputs 10
obj.arrowFunc();   // outputs undefined

Therefore, the choice between arrow and regular functions depends on the need to manage the context and the specifics of usage.