I created a chain API from online resources and I understand it except for one thing, I'm storing "this" in a variable-why? I'm hearing its to capture this to protect it, I'm not entirely sure what that means. Why I'm trying to protect "this" and why I'm a storing it in a variable, what does storing it in a variable do? How does this change "this"? I've done a quick search on here and on google and haven't found an answer. thanks
function Calc(value){
let self= this;//captures this?
self.value=value;//sets the initial value;
self.add=function(addVal){
self.value+=addVal;
return self;
}
self.sub=function(subVal){
self.value-=subVal;
return self;
}
self.mult=function(multVal){
self.value*= multVal;
return self;
}
self.div=function(subVal){
self.value/= subVal;
return self;
}
}
let cal= new Calc(10);
cal.add(2).mult(2).sub(2).div(2);
You're not really storing this
in a variable, you're just storing a reference to the this context variable
in a variable. That is fine but important difference.
Why you do it? Well, this
is a dynamic reference which always references the current context. A new context (or more precisely an Environment Record) is created if you invoke a new function for instance.
So if you wouldn't store the reference from your outer context function Calc
, you could not access it within your sub context's (add, sub, mult, div
) because each of those has it's own this
reference.