我想从闭包外部更改变量“ inner”的值,但我的输出似乎未定义

时间:2019-07-21 09:46:57

标签: javascript closures

我编写了这段代码,试图从闭包外部更改变量“ inner”的值。输出未定义,我想知道为什么。

function welcome(name) {
  var inner = "  to   "

  function innerF(location) {
    let hi = "helo"
    let text = hi + " " + name + " " + "welcome" + inner + location
    return text
  }

  function sayHi() {
    return 'abc'
  }

  function setName(newName) {
    inner = newName;
  }
  return {
    first: innerF,
    second: sayHi,
    third: setName
  }

}
var result = welcome('arpit')
console.log('>>', result.first('ktm'))
console.log('>>', result.third('hari'))

我希望'inner'的值为'hari'

1 个答案:

答案 0 :(得分:1)

您没有在setName()函数中返回值。

function welcome(name) {
  var inner = "  to   "

  function innerF(location) {
    let hi = "helo"
    let text = hi + " " + name + " " + "welcome" + inner + location
    return text
  }

  function sayHi() {
    return 'abc'
  }

  function setName(newName) {
    return inner = newName;
  }
  return {
    first: innerF,
    second: sayHi,
    third: setName
  }

}
var result = welcome('arpit')
console.log('>>', result.first('ktm'))
console.log('>>', result.third('hari'))