x = {}
function f1 () {
this.v1 = 'cool'
try { console.log('v1:', v1) } catch(e){ console.log('error') }
}
f1.bind(x)()
f1()
f1.bind(x)()
f1()
输出:
error
v1: cool
v1: cool
v1: cool
请解释为什么这段代码打印一次error
,然后打印cool
。
为什么没有 this
的 v1
一开始就可以工作?
最佳答案
第二次调用 f1()
而不使用 bind()
- 其中 this
是隐式的 window
,赋值将全局变量 v1
(或 window.v1
)设置为 'cool'
,这就是之后打印的值。
关于javascript - 思维扭曲暗示 this.var 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555724/