0

I have a question. I have been using the this keyword in TypeScript(Angular) for a while now and it is not hard for me. I have been using the this with JavaScript as well. I have just been using it normally. I read that it depends on the context. The this keyword references the window that contains it(or the object?). Any way, I was curious so I ran a test. One test worked, the other one didn't.

Here are the tests

Can any one explain why?

Test 1


This test did not work
var para = document.querySelector('p');
var btn = document.querySelector('button');
var input = document.querySelector('input');

btn.addEventListener('click', onClicked);

function onClicked(){
    var value = this.input.value;
    this.para.textContent = value;
}

Test 2


This test worked
var input = document.querySelector('input');
var p = document.querySelector('p');
var btn = document.querySelector('button');


btn.addEventListener('click', onClicked);

function onClicked(){
    var myInput = input.value;
    p.textContent = myInput;
}

I used the 'this' keyword for the first one, but not for the second one. I thought the 'this' keyword referenced to the scope outside where 'this' is being used. If this is true(pun not intended), then why didn't Test 1 worked. I would have just being referring to the global scope.

Thank you,

Scratch Cat

  • 3
    Read [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Function_context) – Tirafesi May 03 '17 at 13:56
  • To address your specific issue, the callback set in `addEventListener` binds `this` to the element you bound the event to. – Mike Cluck May 03 '17 at 13:58
  • If you wanna know more about how exactly 'this' works, I'd really recommend reading 'this and object prototypes' of YDKJS book series: https://github.com/getify/You-Dont-Know-JS – Gleb Kostyunin May 03 '17 at 14:01
  • I'm really sorry Mike C but it's been a while for me using JS. I don't know what you mean by 'binding' 'this'. But I think I understand. Could you just please clarify what 'binding this' means. – Scratch Cat May 03 '17 at 14:01
  • "binds" is just a fancy way of saying "calls the function with `this` set to the element". –  May 03 '17 at 14:02
  • Oh.... so that means that the variable already has the 'this' word included, just you can't see it? So like this? p.textContent === this.p.textContent already? – Scratch Cat May 03 '17 at 14:04
  • More like `this === btn`. – Mike Cluck May 03 '17 at 14:10

0 Answers0