A recent tweet contained this snippet of JavaScript.
Can someone please explain what is happening in it step by step?
> function dis() { return th
JavaScript scopes are made of Execution Contexts. Each Execution Context has a Lexical Environment (external/globally scoped values), a Variable Environment (locally scoped values), and a this binding.
The this binding is a very important part of the Execution Context. Using call
is one way to alter the this binding, and doing so will automatically create an object to populate the binding with.
Function.prototype.call() (from MDN)
Syntax
fun.call(thisArg[, arg1[, arg2[, ...]]])
thisArg
The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object and primitive values will be converted to objects. (emphasis mine)
Once it is evident that 5 is being converted into new Number(5)
, the rest should be rather obvious. Note that other examples will also work so long as they are primitive values.
function primitiveToObject(prim){
return dis.call(prim);
}
function dis(){ return this; }
//existing example
console.log(primitiveToObject(5));
//Infinity
console.log(primitiveToObject(1/0));
//bool
console.log(primitiveToObject(1>0));
//string
console.log(primitiveToObject("hello world"));
