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