Sunday, July 5, 2015

page 28 of this & OBJECT PROTOTYPES by Kyle Simpson

Revamping my prior .apply example, I continue to cracksmoke my way through the book I came away with through happenstance at this event:

var unassumingAgent = 13;
function whatever(name, taste) {
   this.unassumingAgent = 14;
   alert(name + " likes " + taste + ".");
}
whatever.apply(null, ["Roy", "strawberries"]);
alert(unassumingAgent + " is my lucky number");

 
 

This is bad! This will tell me that 14 is my lucky number when it's not lucky at all! In his book, Mr. Simpson warns of handing in null at .apply and .bind examples to just sidestep an unneeded this when interfacing with third party libraries because if you haven't written the code yourself for all you know it is warping the global object (window) as he puts it or the first step in the call-site chain of presidence. Clearly that is happening here. The solution is to hand in a dummy object you don't care about. The following will tell me that 13 is my luckly number, and yes I know how comic it is that an atheist believes in luck. I see a distinction between the deep end of bullshit and the shallow end (half-assed fun not blinders on commitment) that I will not delve into at this time.

var unassumingAgent = 13;
function whatever(name, taste) {
   this.unassumingAgent = 14;
   alert(name + " likes " + taste + ".");
}
var chaosContainment = new Object;
whatever.apply(chaosContainment, ["Roy", "strawberries"]);
alert(unassumingAgent + " is my lucky number");

 
 

If it's your own code and you are not worried about making an unused this safe, you can use the spread operator in ES6 instead of .apply to clean up your code a little bit and not spec this at all. The code below and the code above both return the same two alerts.

var unassumingAgent = 13;
function whatever(name, taste) {
   alert(name + " likes " + taste + ".");
}
var things = ["Roy", "strawberries"];
whatever(...things);
alert(unassumingAgent + " is my lucky number");

No comments:

Post a Comment