Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null passed as context to a function call

Tags:

javascript

Please explain what hack is used here (I can see that null is passed as a context to a function returning a property of it's context. So I can't clearly understand what is actually happening here.

function getGlobal(){   
  return (function(){   
    return this.dust;   
      }).call(null);
}
like image 266
user1645462 Avatar asked Sep 04 '12 08:09

user1645462


2 Answers

Setting the context to null will make this pointing to the global object. So the code provided will act as accessing the dust property of the global object.

According to the specification of ECMA 262 v5, 10.4.3 Entering Function Code

if thisArg is null or undefined, set the ThisBinding to the global object.

see http://es5.github.com/#x10.4.3

like image 128
qiao Avatar answered Oct 07 '22 18:10

qiao


The trick is to use the fact that if you don't have a receiver of the function, window (in fact the global object of the executed script, hence the name) is used.

So this trick enables to bypass a property (dust) defined in the nearest embedding context and use the one defined in the global object.

like image 23
Denys Séguret Avatar answered Oct 07 '22 17:10

Denys Séguret