【问题标题】:are anonymous functions dynamically scoped?匿名函数是动态范围的吗?
【发布时间】:2018-01-27 14:52:05
【问题描述】:

我还在 Java 中读到匿名函数在封闭函数中引入了一个新范围,而 lambda 表达式是块本地的。这是否意味着上述内容。我对以下示例感到困惑:

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.seconds 将在封闭函数中引入新的 this 作用域。我说的对吗? Static (Lexical) Scoping vs Dynamic Scoping (Pseudocode)

【问题讨论】:

  • this 关键字不称为“范围”,如果您正在寻找的话。
  • “匿名函数”和“lamda表达式”是什么意思?函数表达式和箭头函数都可以是匿名的。
  • 请解释一下
  • 是的,你能解释我在课堂上的作用域
  • 每个函数都创建自己的作用域,无论是匿名函数还是箭头函数,它们总是可以访问外部作用域。范围是你真正写入脚本文件的东西,它不能通过编程方式改变。

标签: javascript anonymous-function


【解决方案1】:

这里的区别是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,而箭头函数则不会。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-13
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多