【问题标题】:This keyword in an Inner Function not working (Javascript)内部函数中的此关键字不起作用(Javascript)
【发布时间】:2023-01-22 19:53:44
【问题描述】:

所以我试图理解 javascript 和内部函数中的 this 关键字。我有一个带有this关键字的内部函数,但它是returning "my hobby is undefined"

我怎样才能让它返回"my hobby is programming"

这是我尝试过但没有用的方法:

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

【问题讨论】:

  • 每个function 都有自己的this,并且基于该函数的调用方式。因为 close() 在没有“上下文”的情况下被调用,所以 closethis 默认为默认全局对象(在浏览器中为 window)。如果你想close使用来自周围范围的this值,那么你可以使它成为一个箭头函数,或者当你在practice内部调用它并通过practice的@时使用.call() 987654338@。这主要在这里涵盖:How does the "this" keyword work, and when should it be used?

标签: javascript function closures this


【解决方案1】:

你的内部函数应该是一个箭头函数,因为一个普通的函数会覆盖 this 上下文:

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

    return close()
}

let person = {
    hobby: "programming"
}

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

希望对您有所帮助!

【讨论】:

    【解决方案2】:

    所以你需要将数据绑定到内部函数里面函数以及将它们绑定到外部函数。您还需要检查是否已经进行了绑定以避免循环。见下文:

    function practice() {
      function close() {
        console.log(`my hobby is ${this.hobby}`)
      }
      let binding2
      if (!binding2) binding2 = close.bind(this)
      
      return binding2()
    }
    
    let person = {
      hobby: "programming"
    }
    let binding = practice.bind(person)
    binding()

    【讨论】:

    • 你在这里指的是什么循环?您可以直接执行 let bidnging2 = close.bind(this); 而无需 if 语句。但是,如果您这样做后直接调用 binding2(),您不妨改用 binding2.call(this) :)
    • 你是对的,出于某种原因,当我测试代码时,在我发布它之前,我得到了一个循环所以添加以避免它哈哈
    • 也许你可以edit你的答案来修复你的那部分答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2016-07-17
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    相关资源
    最近更新 更多