当您在全局范围内编写时,somefunc() = 100您为该somefunc函数定义了一个新方法。这有两个效果:
somefunc未定义,则将其设为const x = 123绑定到新通用函数的常量(即不能像 一样重新分配)。() -> 100方法somefunc。事实上, for 的绑定somefunc是恒定的,这就是为什么您之后无法重新分配它的原因。这对于性能非常重要,因为非常量全局变量的性能非常差;如果函数绑定不是恒定的,那么任何时候调用函数都会很慢。
即使您无法更改函数somefunc引用的内容,您也可以通过向函数添加方法甚至覆盖现有方法来更改函数本身。例如,稍后编写somefunc() = 200不会创建新函数,而是用返回 200 而不是 100 的新方法替换该函数不带参数的方法。
当你写:
somefunc() = 100
Run Code Online (Sandbox Code Playgroud)
它只是一个简写
function somefunc()
return 100
end
Run Code Online (Sandbox Code Playgroud)
因此,即使有一个=符号,即赋值运算符,它与写作不同x = 100,后者只是将值绑定到100name x。特别注意写例如:
somefunc = () -> 100
Run Code Online (Sandbox Code Playgroud)
允许您编写somefunc()和获取100。但这次您可以稍后再写somefunc = 100,因为它somefunc = () -> 100不是函数定义,而是将匿名函数绑定() -> 100到名称的赋值somefunc。