Home > database >  This keyword in an Inner Function not working (Javascript)
This keyword in an Inner Function not working (Javascript)

Time:01-23

So I am trying to understand the this keyword in javascript and inner functions. and I have an inner function with the this keyword but it is returning "my hobby is undefined".

How can I make it return "my hobby is programming"

Here is what I tried and it did not work:

function practice() {
  function close() {
    console.log(`my hobby is ${this.hobby}`)
  }
  
  return close()
}

let person = {
  hobby: "programming"
}

let binding = practice.bind(person)
console.log(binding())

CodePudding user response:

You inner function should be an arrow function because a normal one overwrites the this context :

function practice() {
    const close = () => {
        return `my hobby is ${ this.hobby }`
    }

    return close()
}

let person = {
    hobby: "programming"
}

let binding = practice.bind(person)
console.log(binding())

Hope it helped you !

CodePudding user response:

So you would need to bind the data to the inner function inside the function as well as binding them to the outer one. See below:

function practice() {
  function close() {
    console.log(`my hobby is ${this.hobby}`)
  }
  let binding2 = close.bind(this)
  
  return binding2()
}

let person = {
  hobby: "programming"
}
let binding = practice.bind(person)
binding()

  • Related