In the console tab of chrome developer tools, I typed this, and it has shown Window object. How this becomes window object here?
console.log(this);
Consider below snippet
var firstname = "Javascript";
var lastname = "Lover - SKT";
function getName() {
this.firstname = "Sivakumar";
this.lastname = "Tadisetti";
}
console.log(firstname);
getName();
console.log(this.lastname); // How this.lastname is working here?
I've read the following StackOverflow answers
But didn't understand how the above snippet is working (The line I commented)
Update:
I have tried above code snippet in jsfiddle where it outputs this.firstname is undefined. So that's the reason I am asking this question. But in the stackoverflow code snippet it is working fine
thisis thewindow, and after callinggetNames(), you are changingwindow.firstnameandwindow.lastname. so in the second log, they are modifiedlastnameis declared as global variable and it can be used aswindow.lastname