匿名函数是动态范围的吗?
are anonymous functions dynamically scoped?
我在 Java 中还读到,匿名函数在封闭函数中引入了一个新范围,而 lambda 表达式是块状的 -local.Does 这意味着 above.I 与以下示例混淆:
var timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++
}, 1000)
}
}
// When an item is searched, it starts from the anonymous function
// and this doesn't mean the same as parent this.
// This means that we can access this .seconds by first going to
// its enclosing function in the arrow expression.
timer.start()
setTimeout(function () {
console.log(timer.seconds)
}, 3500)
这里this.seconds如果是匿名的话,会在封闭函数中引入一个新的this作用域function.Am对吗?
Static (Lexical) Scoping vs Dynamic Scoping (Pseudocode)
这里的区别是this
。箭头函数不会更改 this
的值,而使用 function
关键字创建的函数会更改。
这就是为什么您上面的代码和下面的代码不同的原因:
var timer = {
seconds: 0,
start() {
setInterval(function(){
this.seconds++
}, 1000)
}
}
// When an item is searched, it starts from the anonymous function
// and this doesn't mean the same as parent this.
// This means that we can access this .seconds by first going to
// its enclosing function in the arrow expression.
timer.start()
setTimeout(function () {
console.log(timer.seconds)
}, 3500)
在此代码中,function(){
将 this
的值覆盖为自身,因此不再有秒变量。
传统匿名函数和箭头函数在作用域(函数可以访问哪些变量)上没有区别,只是传统匿名函数创建了一个新的 this
而箭头函数没有。
我在 Java 中还读到,匿名函数在封闭函数中引入了一个新范围,而 lambda 表达式是块状的 -local.Does 这意味着 above.I 与以下示例混淆:
var timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++
}, 1000)
}
}
// When an item is searched, it starts from the anonymous function
// and this doesn't mean the same as parent this.
// This means that we can access this .seconds by first going to
// its enclosing function in the arrow expression.
timer.start()
setTimeout(function () {
console.log(timer.seconds)
}, 3500)
这里this.seconds如果是匿名的话,会在封闭函数中引入一个新的this作用域function.Am对吗? Static (Lexical) Scoping vs Dynamic Scoping (Pseudocode)
这里的区别是this
。箭头函数不会更改 this
的值,而使用 function
关键字创建的函数会更改。
这就是为什么您上面的代码和下面的代码不同的原因:
var timer = {
seconds: 0,
start() {
setInterval(function(){
this.seconds++
}, 1000)
}
}
// When an item is searched, it starts from the anonymous function
// and this doesn't mean the same as parent this.
// This means that we can access this .seconds by first going to
// its enclosing function in the arrow expression.
timer.start()
setTimeout(function () {
console.log(timer.seconds)
}, 3500)
在此代码中,function(){
将 this
的值覆盖为自身,因此不再有秒变量。
传统匿名函数和箭头函数在作用域(函数可以访问哪些变量)上没有区别,只是传统匿名函数创建了一个新的 this
而箭头函数没有。