简体   繁体   中英

This keyword in an Inner Function not working (Javascript)

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())

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 !

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM