0

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);
Samatha
  • 35
  • 5
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Erazihel Mar 21 '17 at 13:13
  • The code shown would produce the same result if you used `this` everywhere that you currently have `self`. – nnnnnn Mar 21 '17 at 13:16

1 Answers1

1

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.

jAndy
  • 212,463
  • 51
  • 293
  • 348
  • Except that if we changed that code to use `this` everywhere instead of `self` it would still produce the same result, because of the way the functions are being called. – nnnnnn Mar 21 '17 at 13:16
  • True. The type of invocation decides the reference of `this` unless it was bound otherwise. I just didn't want to go into greater detail. In general, it is most important here to understand the dynamic nature of `this` for the OP imo. – jAndy Mar 21 '17 at 13:26