javascript - 思维扭曲暗示 this.var 访问

标签 javascript

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

为什么没有 thisv1 一开始就可以工作?

最佳答案

第二次调用 f1() 而不使用 bind() - 其中 this 是隐式的 window,赋值将全局变量 v1(或 window.v1)设置为 'cool',这就是之后打印的值。

关于javascript - 思维扭曲暗示 this.var 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555724/

相关文章:

javascript - 我已经在 python 中创建了一个列表,但是如何在 javascript 中迭代这个列表?

javascript - 在 Javascript 中过滤数组

php - jQuery jQGrid 在标题层单击时展开/折叠网格

javascript - 文本输入 : Limit input to numbers (0-9) and the minus sign (-). 未按预期工作

javascript - md-autocomplete 在选择项目后模糊自身

javascript - JQuery 生成的小书签未在某些网站上运行

Javascript 无法正确排序包含两个数组值的数组

javascript - 如何使用 HTML 或 Javascript 将用户输入的网站识别为链接标签?

javascript - 现有 javascript 库的最小 typescript 定义

javascript - JS : Event not showing in Google Analytics