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
Please explain why this code prints error once, and then cool.
Why would v1 without this work at all in the first place?
The second call to f1() without bind() - where this is implicitly window, assigns the global variable v1 (or window.v1) to 'cool' and that is the value that is printed thereafter.
Interesting question.
Why can you use the v1 without this keyword ?
Because your "this" keyword will be bound to "window" object, which is special. In case of window, the variable object is the same as its "this" object/context.
Simply put, variables and properties on window object are one and the same.
Below is an example from ECMA-262.
var a = new String('test');
alert(a); // directly, is found in VO(globalContext): "test"
alert(window['a']); // indirectly via global === VO(globalContext): "test"
alert(a === this.a); // true
var aKey = 'a';
alert(window[aKey]); // indirectly, with dynamic property name: "test"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With