x
# Error: object 'x' not found

(function() { x <<- 1 })()
x
# [1] 1

(function() { if (TRUE) { y <- 1 }; print(y) })()
# [1] 1

(function() { if (FALSE) { y <- 1 }; print(y) })()
# Error in print(y) : object 'y' not found

(function() { print(y); y <- 1 })()
# Error in print(y) : object 'y' not found

可以这很 JavaScript (除了最后两条。)

Update:

R:

(function () { a <<- 1; a <- 2 })() # variable definitions are *not* hoisted in R.
a
# 1

JS:

(function () { a = 1; var a = 2 /* `var` is hoisted, but not the initial assignment */; })()
a
// Error: 'a' is undefined

_CRY
1.2k 声望24 粉丝

How dare we sit quietly