Search code examples
javascriptfunctionarrow-functions

java script arrow functions


i made a button called btn and i gave it a text

btn = document.createElement('button')
btn.textContent = "Hello World"

i want to make it alert its textContent when it gets clicked.

i know i can use:

btn.onclick = function(){alert(this.textContent)}

but lately i have learnt about these arrow functions and i wanted to use it here so i made this

btn.onclick = ()=>{alert(this.textContent)}

and

btn.onclick = ()=> alert(this.textContent)

but both of them alert undefined

so how can i make it ?


Solution

  • this indicates its parent scope in arrow function, while it indicates button component in regular function. So in arrow function, you need to use btn.textContent instead of this.textContent

    btn = document.createElement('button')
    btn.textContent = "Hello World"
    // btn.onclick = function(){alert(this.textContent)}
    btn.onclick = (event) => {alert(event.target.textContent)}
    document.body.appendChild(btn);

    btn = document.createElement('button')
    btn.textContent = "Hello World"
    btn.onclick = function(){alert(this.textContent)}
    // btn.onclick = (event) => {alert(event.target.textContent)}
    document.body.appendChild(btn);