[Javascript] Why need arrow function?

Zhentiw發表於2024-10-06

Eliminate the ambiguity of the function

What ambiguity means?

Normally a function can do two things

1. Instruction sequence

2. Contruction

function a() {}

a() // run the function, instruction sequence
new a() // construction

In javascript, when you see a function, you cannot make sure how to call that function

Number()
new Number()
Date()
new Date()

After ES6, introduce arrow function and class

class: you can only use it with construction

arrow function: you can only use it with instruction sequence

class A {}
new A() // OK
A() // Error

const a = () => {}
a() // OK
new a() // Error

So now, you should know that arrow function has nothing to do with all the things which related to OOP, such as new, this, prototype

console.log(a.prototype) // undefined

相關文章