我编写了这段代码,试图从闭包外部更改变量“ 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'
答案 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'))