Kuidas erineb noolefunktsioonide kasutamine standardfunktsioonidest JavaScriptis?
sobes.tech AI
Vastus AI-lt
Arrow functions in JavaScript differ from standard functions in several key aspects:
-
thiscontext: In arrow functions,thisis lexically inherited from the surrounding context, meaning it does not create its ownthiscontext. In regular functions,thisdepends on how the function is called. -
Absence of
arguments: Arrow functions do not have their ownargumentsobject. To access arguments, parameters or external variables should be used. -
Cannot be used as constructors: Arrow functions cannot be invoked with
newbecause 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.