Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mind twisting implied this.var access

Tags:

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()

Output:

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?

like image 928
exebook Avatar asked Jun 18 '26 08:06

exebook


2 Answers

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.

like image 115
techfoobar Avatar answered Jun 19 '26 22:06

techfoobar


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"
like image 24
Rainer Plumer Avatar answered Jun 19 '26 20:06

Rainer Plumer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!