javascript - Mind twisting implied this.var access -
x = {} function f1 () { this.v1 = 'cool' try { console.log('v1:', v1) } catch(e){ console.log('error') } } f1.bind(x)() f1() f1.bind(x)() f1()
output:
error v1: cool v1: cool v1: cool
please explain why code prints error
once, , cool
.
why v1
without this
work @ in first place?
first, you're logging not this.v1
, v1
. reference global v1
variable supposed defined on window
. every time log not x.v1
, window.v1
.
this
in function without bounded scope refers global window
. when call first time, v1
created on x
, when call second time, created on window
.
Comments
Post a Comment